babylon.max.js 4.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. var scene = this._mesh.getScene();
  101. for (var index = 0; index < scene.meshes.length; index++) {
  102. var otherMesh = scene.meshes[index];
  103. if (!otherMesh.material) {
  104. continue;
  105. }
  106. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  107. continue;
  108. }
  109. if (otherMesh.material.getEffect() === effect) {
  110. otherMesh.computeBonesUsingShaders = false;
  111. }
  112. else {
  113. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  114. var subMesh = _a[_i];
  115. var subMeshEffect = subMesh.effect;
  116. if (subMeshEffect === effect) {
  117. otherMesh.computeBonesUsingShaders = false;
  118. break;
  119. }
  120. }
  121. }
  122. }
  123. }
  124. else {
  125. var currentFallbacks = this._defines[this._currentRank];
  126. if (currentFallbacks) {
  127. for (var index = 0; index < currentFallbacks.length; index++) {
  128. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  129. }
  130. }
  131. this._currentRank++;
  132. }
  133. return currentDefines;
  134. };
  135. return EffectFallbacks;
  136. }());
  137. BABYLON.EffectFallbacks = EffectFallbacks;
  138. /**
  139. * Options to be used when creating an effect.
  140. */
  141. var EffectCreationOptions = /** @class */ (function () {
  142. function EffectCreationOptions() {
  143. }
  144. return EffectCreationOptions;
  145. }());
  146. BABYLON.EffectCreationOptions = EffectCreationOptions;
  147. /**
  148. * Effect containing vertex and fragment shader that can be executed on an object.
  149. */
  150. var Effect = /** @class */ (function () {
  151. /**
  152. * Instantiates an effect.
  153. * An effect can be used to create/manage/execute vertex and fragment shaders.
  154. * @param baseName Name of the effect.
  155. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  156. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  157. * @param samplers List of sampler variables that will be passed to the shader.
  158. * @param engine Engine to be used to render the effect
  159. * @param defines Define statements to be added to the shader.
  160. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  161. * @param onCompiled Callback that will be called when the shader is compiled.
  162. * @param onError Callback that will be called if an error occurs during shader compilation.
  163. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  164. */
  165. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  166. if (samplers === void 0) { samplers = null; }
  167. if (defines === void 0) { defines = null; }
  168. if (fallbacks === void 0) { fallbacks = null; }
  169. if (onCompiled === void 0) { onCompiled = null; }
  170. if (onError === void 0) { onError = null; }
  171. var _this = this;
  172. /**
  173. * Unique ID of the effect.
  174. */
  175. this.uniqueId = 0;
  176. /**
  177. * Observable that will be called when the shader is compiled.
  178. */
  179. this.onCompileObservable = new BABYLON.Observable();
  180. /**
  181. * Observable that will be called if an error occurs during shader compilation.
  182. */
  183. this.onErrorObservable = new BABYLON.Observable();
  184. /**
  185. * Observable that will be called when effect is bound.
  186. */
  187. this.onBindObservable = new BABYLON.Observable();
  188. this._uniformBuffersNames = {};
  189. this._isReady = false;
  190. this._compilationError = "";
  191. this.name = baseName;
  192. if (attributesNamesOrOptions.attributes) {
  193. var options = attributesNamesOrOptions;
  194. this._engine = uniformsNamesOrEngine;
  195. this._attributesNames = options.attributes;
  196. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  197. this._samplers = options.samplers.slice();
  198. this.defines = options.defines;
  199. this.onError = options.onError;
  200. this.onCompiled = options.onCompiled;
  201. this._fallbacks = options.fallbacks;
  202. this._indexParameters = options.indexParameters;
  203. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  204. if (options.uniformBuffersNames) {
  205. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  206. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  207. }
  208. }
  209. }
  210. else {
  211. this._engine = engine;
  212. this.defines = defines;
  213. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  214. this._samplers = samplers ? samplers.slice() : [];
  215. this._attributesNames = attributesNamesOrOptions;
  216. this.onError = onError;
  217. this.onCompiled = onCompiled;
  218. this._indexParameters = indexParameters;
  219. this._fallbacks = fallbacks;
  220. }
  221. this.uniqueId = Effect._uniqueIdSeed++;
  222. var vertexSource;
  223. var fragmentSource;
  224. if (baseName.vertexElement) {
  225. vertexSource = document.getElementById(baseName.vertexElement);
  226. if (!vertexSource) {
  227. vertexSource = baseName.vertexElement;
  228. }
  229. }
  230. else {
  231. vertexSource = baseName.vertex || baseName;
  232. }
  233. if (baseName.fragmentElement) {
  234. fragmentSource = document.getElementById(baseName.fragmentElement);
  235. if (!fragmentSource) {
  236. fragmentSource = baseName.fragmentElement;
  237. }
  238. }
  239. else {
  240. fragmentSource = baseName.fragment || baseName;
  241. }
  242. this._loadVertexShader(vertexSource, function (vertexCode) {
  243. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  244. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  245. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  246. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  247. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  248. if (baseName) {
  249. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  250. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  251. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  252. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  253. }
  254. else {
  255. _this._vertexSourceCode = migratedVertexCode;
  256. _this._fragmentSourceCode = migratedFragmentCode;
  257. }
  258. _this._prepareEffect();
  259. });
  260. });
  261. });
  262. });
  263. });
  264. });
  265. }
  266. Object.defineProperty(Effect.prototype, "key", {
  267. /**
  268. * Unique key for this effect
  269. */
  270. get: function () {
  271. return this._key;
  272. },
  273. enumerable: true,
  274. configurable: true
  275. });
  276. /**
  277. * If the effect has been compiled and prepared.
  278. * @returns if the effect is compiled and prepared.
  279. */
  280. Effect.prototype.isReady = function () {
  281. return this._isReady;
  282. };
  283. /**
  284. * The engine the effect was initialized with.
  285. * @returns the engine.
  286. */
  287. Effect.prototype.getEngine = function () {
  288. return this._engine;
  289. };
  290. /**
  291. * The compiled webGL program for the effect
  292. * @returns the webGL program.
  293. */
  294. Effect.prototype.getProgram = function () {
  295. return this._program;
  296. };
  297. /**
  298. * The set of names of attribute variables for the shader.
  299. * @returns An array of attribute names.
  300. */
  301. Effect.prototype.getAttributesNames = function () {
  302. return this._attributesNames;
  303. };
  304. /**
  305. * Returns the attribute at the given index.
  306. * @param index The index of the attribute.
  307. * @returns The location of the attribute.
  308. */
  309. Effect.prototype.getAttributeLocation = function (index) {
  310. return this._attributes[index];
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param name of the attribute to look up.
  315. * @returns the attribute location.
  316. */
  317. Effect.prototype.getAttributeLocationByName = function (name) {
  318. var index = this._attributesNames.indexOf(name);
  319. return this._attributes[index];
  320. };
  321. /**
  322. * The number of attributes.
  323. * @returns the numnber of attributes.
  324. */
  325. Effect.prototype.getAttributesCount = function () {
  326. return this._attributes.length;
  327. };
  328. /**
  329. * Gets the index of a uniform variable.
  330. * @param uniformName of the uniform to look up.
  331. * @returns the index.
  332. */
  333. Effect.prototype.getUniformIndex = function (uniformName) {
  334. return this._uniformsNames.indexOf(uniformName);
  335. };
  336. /**
  337. * Returns the attribute based on the name of the variable.
  338. * @param uniformName of the uniform to look up.
  339. * @returns the location of the uniform.
  340. */
  341. Effect.prototype.getUniform = function (uniformName) {
  342. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  343. };
  344. /**
  345. * Returns an array of sampler variable names
  346. * @returns The array of sampler variable neames.
  347. */
  348. Effect.prototype.getSamplers = function () {
  349. return this._samplers;
  350. };
  351. /**
  352. * The error from the last compilation.
  353. * @returns the error string.
  354. */
  355. Effect.prototype.getCompilationError = function () {
  356. return this._compilationError;
  357. };
  358. /**
  359. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  360. * @param func The callback to be used.
  361. */
  362. Effect.prototype.executeWhenCompiled = function (func) {
  363. if (this.isReady()) {
  364. func(this);
  365. return;
  366. }
  367. this.onCompileObservable.add(function (effect) {
  368. func(effect);
  369. });
  370. };
  371. /** @hidden */
  372. Effect.prototype._loadVertexShader = function (vertex, callback) {
  373. if (BABYLON.Tools.IsWindowObjectExist()) {
  374. // DOM element ?
  375. if (vertex instanceof HTMLElement) {
  376. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  377. callback(vertexCode);
  378. return;
  379. }
  380. }
  381. // Base64 encoded ?
  382. if (vertex.substr(0, 7) === "base64:") {
  383. var vertexBinary = window.atob(vertex.substr(7));
  384. callback(vertexBinary);
  385. return;
  386. }
  387. // Is in local store ?
  388. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  389. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  390. return;
  391. }
  392. var vertexShaderUrl;
  393. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  394. vertexShaderUrl = vertex;
  395. }
  396. else {
  397. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  398. }
  399. // Vertex shader
  400. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  401. };
  402. /** @hidden */
  403. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  404. if (BABYLON.Tools.IsWindowObjectExist()) {
  405. // DOM element ?
  406. if (fragment instanceof HTMLElement) {
  407. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  408. callback(fragmentCode);
  409. return;
  410. }
  411. }
  412. // Base64 encoded ?
  413. if (fragment.substr(0, 7) === "base64:") {
  414. var fragmentBinary = window.atob(fragment.substr(7));
  415. callback(fragmentBinary);
  416. return;
  417. }
  418. // Is in local store ?
  419. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  420. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  421. return;
  422. }
  423. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  424. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  425. return;
  426. }
  427. var fragmentShaderUrl;
  428. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  429. fragmentShaderUrl = fragment;
  430. }
  431. else {
  432. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  433. }
  434. // Fragment shader
  435. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  436. };
  437. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  438. // Rebuild shaders source code
  439. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  440. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  441. vertexCode = prefix + vertexCode;
  442. fragmentCode = prefix + fragmentCode;
  443. // Number lines of shaders source code
  444. var i = 2;
  445. var regex = /\n/gm;
  446. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  447. i = 2;
  448. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  449. // Dump shaders name and formatted source code
  450. if (this.name.vertexElement) {
  451. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  452. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  453. }
  454. else if (this.name.vertex) {
  455. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  456. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  457. }
  458. else {
  459. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  460. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  461. }
  462. };
  463. ;
  464. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  465. var preparedSourceCode = this._processPrecision(sourceCode);
  466. if (this._engine.webGLVersion == 1) {
  467. callback(preparedSourceCode);
  468. return;
  469. }
  470. // Already converted
  471. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  472. callback(preparedSourceCode.replace("#version 300 es", ""));
  473. return;
  474. }
  475. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  476. // Remove extensions
  477. // #extension GL_OES_standard_derivatives : enable
  478. // #extension GL_EXT_shader_texture_lod : enable
  479. // #extension GL_EXT_frag_depth : enable
  480. // #extension GL_EXT_draw_buffers : require
  481. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  482. var result = preparedSourceCode.replace(regex, "");
  483. // Migrate to GLSL v300
  484. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  485. result = result.replace(/attribute[ \t]/g, "in ");
  486. result = result.replace(/[ \t]attribute/g, " in");
  487. if (isFragment) {
  488. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  489. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  490. result = result.replace(/texture2D\s*\(/g, "texture(");
  491. result = result.replace(/textureCube\s*\(/g, "texture(");
  492. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  493. result = result.replace(/gl_FragColor/g, "glFragColor");
  494. result = result.replace(/gl_FragData/g, "glFragData");
  495. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  496. }
  497. callback(result);
  498. };
  499. Effect.prototype._processIncludes = function (sourceCode, callback) {
  500. var _this = this;
  501. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  502. var match = regex.exec(sourceCode);
  503. var returnValue = new String(sourceCode);
  504. while (match != null) {
  505. var includeFile = match[1];
  506. // Uniform declaration
  507. if (includeFile.indexOf("__decl__") !== -1) {
  508. includeFile = includeFile.replace(/__decl__/, "");
  509. if (this._engine.supportsUniformBuffers) {
  510. includeFile = includeFile.replace(/Vertex/, "Ubo");
  511. includeFile = includeFile.replace(/Fragment/, "Ubo");
  512. }
  513. includeFile = includeFile + "Declaration";
  514. }
  515. if (Effect.IncludesShadersStore[includeFile]) {
  516. // Substitution
  517. var includeContent = Effect.IncludesShadersStore[includeFile];
  518. if (match[2]) {
  519. var splits = match[3].split(",");
  520. for (var index = 0; index < splits.length; index += 2) {
  521. var source = new RegExp(splits[index], "g");
  522. var dest = splits[index + 1];
  523. includeContent = includeContent.replace(source, dest);
  524. }
  525. }
  526. if (match[4]) {
  527. var indexString = match[5];
  528. if (indexString.indexOf("..") !== -1) {
  529. var indexSplits = indexString.split("..");
  530. var minIndex = parseInt(indexSplits[0]);
  531. var maxIndex = parseInt(indexSplits[1]);
  532. var sourceIncludeContent = includeContent.slice(0);
  533. includeContent = "";
  534. if (isNaN(maxIndex)) {
  535. maxIndex = this._indexParameters[indexSplits[1]];
  536. }
  537. for (var i = minIndex; i < maxIndex; i++) {
  538. if (!this._engine.supportsUniformBuffers) {
  539. // Ubo replacement
  540. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  541. return p1 + "{X}";
  542. });
  543. }
  544. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  545. }
  546. }
  547. else {
  548. if (!this._engine.supportsUniformBuffers) {
  549. // Ubo replacement
  550. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  551. return p1 + "{X}";
  552. });
  553. }
  554. includeContent = includeContent.replace(/\{X\}/g, indexString);
  555. }
  556. }
  557. // Replace
  558. returnValue = returnValue.replace(match[0], includeContent);
  559. }
  560. else {
  561. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  562. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  563. Effect.IncludesShadersStore[includeFile] = fileContent;
  564. _this._processIncludes(returnValue, callback);
  565. });
  566. return;
  567. }
  568. match = regex.exec(sourceCode);
  569. }
  570. callback(returnValue);
  571. };
  572. Effect.prototype._processPrecision = function (source) {
  573. if (source.indexOf("precision highp float") === -1) {
  574. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  575. source = "precision mediump float;\n" + source;
  576. }
  577. else {
  578. source = "precision highp float;\n" + source;
  579. }
  580. }
  581. else {
  582. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  583. source = source.replace("precision highp float", "precision mediump float");
  584. }
  585. }
  586. return source;
  587. };
  588. /**
  589. * Recompiles the webGL program
  590. * @param vertexSourceCode The source code for the vertex shader.
  591. * @param fragmentSourceCode The source code for the fragment shader.
  592. * @param onCompiled Callback called when completed.
  593. * @param onError Callback called on error.
  594. */
  595. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  596. var _this = this;
  597. this._isReady = false;
  598. this._vertexSourceCodeOverride = vertexSourceCode;
  599. this._fragmentSourceCodeOverride = fragmentSourceCode;
  600. this.onError = function (effect, error) {
  601. if (onError) {
  602. onError(error);
  603. }
  604. };
  605. this.onCompiled = function () {
  606. var scenes = _this.getEngine().scenes;
  607. for (var i = 0; i < scenes.length; i++) {
  608. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  609. }
  610. if (onCompiled) {
  611. onCompiled(_this._program);
  612. }
  613. };
  614. this._fallbacks = null;
  615. this._prepareEffect();
  616. };
  617. /**
  618. * Gets the uniform locations of the the specified variable names
  619. * @param names THe names of the variables to lookup.
  620. * @returns Array of locations in the same order as variable names.
  621. */
  622. Effect.prototype.getSpecificUniformLocations = function (names) {
  623. var engine = this._engine;
  624. return engine.getUniforms(this._program, names);
  625. };
  626. /**
  627. * Prepares the effect
  628. */
  629. Effect.prototype._prepareEffect = function () {
  630. var attributesNames = this._attributesNames;
  631. var defines = this.defines;
  632. var fallbacks = this._fallbacks;
  633. this._valueCache = {};
  634. var previousProgram = this._program;
  635. try {
  636. var engine = this._engine;
  637. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  638. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  639. }
  640. else {
  641. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  642. }
  643. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  644. if (engine.supportsUniformBuffers) {
  645. for (var name in this._uniformBuffersNames) {
  646. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  647. }
  648. }
  649. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  650. this._attributes = engine.getAttributes(this._program, attributesNames);
  651. var index;
  652. for (index = 0; index < this._samplers.length; index++) {
  653. var sampler = this.getUniform(this._samplers[index]);
  654. if (sampler == null) {
  655. this._samplers.splice(index, 1);
  656. index--;
  657. }
  658. }
  659. engine.bindSamplers(this);
  660. this._compilationError = "";
  661. this._isReady = true;
  662. if (this.onCompiled) {
  663. this.onCompiled(this);
  664. }
  665. this.onCompileObservable.notifyObservers(this);
  666. this.onCompileObservable.clear();
  667. // Unbind mesh reference in fallbacks
  668. if (this._fallbacks) {
  669. this._fallbacks.unBindMesh();
  670. }
  671. if (previousProgram) {
  672. this.getEngine()._deleteProgram(previousProgram);
  673. }
  674. }
  675. catch (e) {
  676. this._compilationError = e.message;
  677. // Let's go through fallbacks then
  678. BABYLON.Tools.Error("Unable to compile effect:");
  679. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  680. return " " + uniform;
  681. }));
  682. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  683. return " " + attribute;
  684. }));
  685. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  686. BABYLON.Tools.Error("Error: " + this._compilationError);
  687. if (previousProgram) {
  688. this._program = previousProgram;
  689. this._isReady = true;
  690. if (this.onError) {
  691. this.onError(this, this._compilationError);
  692. }
  693. this.onErrorObservable.notifyObservers(this);
  694. }
  695. if (fallbacks && fallbacks.isMoreFallbacks) {
  696. BABYLON.Tools.Error("Trying next fallback.");
  697. this.defines = fallbacks.reduce(this.defines, this);
  698. this._prepareEffect();
  699. }
  700. else { // Sorry we did everything we can
  701. if (this.onError) {
  702. this.onError(this, this._compilationError);
  703. }
  704. this.onErrorObservable.notifyObservers(this);
  705. this.onErrorObservable.clear();
  706. // Unbind mesh reference in fallbacks
  707. if (this._fallbacks) {
  708. this._fallbacks.unBindMesh();
  709. }
  710. }
  711. }
  712. };
  713. Object.defineProperty(Effect.prototype, "isSupported", {
  714. /**
  715. * Checks if the effect is supported. (Must be called after compilation)
  716. */
  717. get: function () {
  718. return this._compilationError === "";
  719. },
  720. enumerable: true,
  721. configurable: true
  722. });
  723. /**
  724. * Binds a texture to the engine to be used as output of the shader.
  725. * @param channel Name of the output variable.
  726. * @param texture Texture to bind.
  727. */
  728. Effect.prototype._bindTexture = function (channel, texture) {
  729. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  730. };
  731. /**
  732. * Sets a texture on the engine to be used in the shader.
  733. * @param channel Name of the sampler variable.
  734. * @param texture Texture to set.
  735. */
  736. Effect.prototype.setTexture = function (channel, texture) {
  737. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  738. };
  739. /**
  740. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  741. * @param channel Name of the sampler variable.
  742. * @param texture Texture to set.
  743. */
  744. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  745. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  746. };
  747. /**
  748. * Sets an array of textures on the engine to be used in the shader.
  749. * @param channel Name of the variable.
  750. * @param textures Textures to set.
  751. */
  752. Effect.prototype.setTextureArray = function (channel, textures) {
  753. if (this._samplers.indexOf(channel + "Ex") === -1) {
  754. var initialPos = this._samplers.indexOf(channel);
  755. for (var index = 1; index < textures.length; index++) {
  756. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  757. }
  758. }
  759. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  760. };
  761. /**
  762. * 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)
  763. * @param channel Name of the sampler variable.
  764. * @param postProcess Post process to get the input texture from.
  765. */
  766. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  767. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  768. };
  769. /**
  770. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  771. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  772. * @param channel Name of the sampler variable.
  773. * @param postProcess Post process to get the output texture from.
  774. */
  775. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  776. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  777. };
  778. /** @hidden */
  779. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  780. var cache = this._valueCache[uniformName];
  781. var flag = matrix.updateFlag;
  782. if (cache !== undefined && cache === flag) {
  783. return false;
  784. }
  785. this._valueCache[uniformName] = flag;
  786. return true;
  787. };
  788. /** @hidden */
  789. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  790. var cache = this._valueCache[uniformName];
  791. if (!cache) {
  792. cache = [x, y];
  793. this._valueCache[uniformName] = cache;
  794. return true;
  795. }
  796. var changed = false;
  797. if (cache[0] !== x) {
  798. cache[0] = x;
  799. changed = true;
  800. }
  801. if (cache[1] !== y) {
  802. cache[1] = y;
  803. changed = true;
  804. }
  805. return changed;
  806. };
  807. /** @hidden */
  808. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  809. var cache = this._valueCache[uniformName];
  810. if (!cache) {
  811. cache = [x, y, z];
  812. this._valueCache[uniformName] = cache;
  813. return true;
  814. }
  815. var changed = false;
  816. if (cache[0] !== x) {
  817. cache[0] = x;
  818. changed = true;
  819. }
  820. if (cache[1] !== y) {
  821. cache[1] = y;
  822. changed = true;
  823. }
  824. if (cache[2] !== z) {
  825. cache[2] = z;
  826. changed = true;
  827. }
  828. return changed;
  829. };
  830. /** @hidden */
  831. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  832. var cache = this._valueCache[uniformName];
  833. if (!cache) {
  834. cache = [x, y, z, w];
  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. if (cache[3] !== w) {
  852. cache[3] = w;
  853. changed = true;
  854. }
  855. return changed;
  856. };
  857. /**
  858. * Binds a buffer to a uniform.
  859. * @param buffer Buffer to bind.
  860. * @param name Name of the uniform variable to bind to.
  861. */
  862. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  863. var bufferName = this._uniformBuffersNames[name];
  864. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  865. return;
  866. }
  867. Effect._baseCache[bufferName] = buffer;
  868. this._engine.bindUniformBufferBase(buffer, bufferName);
  869. };
  870. /**
  871. * Binds block to a uniform.
  872. * @param blockName Name of the block to bind.
  873. * @param index Index to bind.
  874. */
  875. Effect.prototype.bindUniformBlock = function (blockName, index) {
  876. this._engine.bindUniformBlock(this._program, blockName, index);
  877. };
  878. /**
  879. * Sets an interger value on a uniform variable.
  880. * @param uniformName Name of the variable.
  881. * @param value Value to be set.
  882. * @returns this effect.
  883. */
  884. Effect.prototype.setInt = function (uniformName, value) {
  885. var cache = this._valueCache[uniformName];
  886. if (cache !== undefined && cache === value)
  887. return this;
  888. this._valueCache[uniformName] = value;
  889. this._engine.setInt(this.getUniform(uniformName), value);
  890. return this;
  891. };
  892. /**
  893. * Sets an int array on a uniform variable.
  894. * @param uniformName Name of the variable.
  895. * @param array array to be set.
  896. * @returns this effect.
  897. */
  898. Effect.prototype.setIntArray = function (uniformName, array) {
  899. this._valueCache[uniformName] = null;
  900. this._engine.setIntArray(this.getUniform(uniformName), array);
  901. return this;
  902. };
  903. /**
  904. * 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)
  905. * @param uniformName Name of the variable.
  906. * @param array array to be set.
  907. * @returns this effect.
  908. */
  909. Effect.prototype.setIntArray2 = function (uniformName, array) {
  910. this._valueCache[uniformName] = null;
  911. this._engine.setIntArray2(this.getUniform(uniformName), array);
  912. return this;
  913. };
  914. /**
  915. * 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)
  916. * @param uniformName Name of the variable.
  917. * @param array array to be set.
  918. * @returns this effect.
  919. */
  920. Effect.prototype.setIntArray3 = function (uniformName, array) {
  921. this._valueCache[uniformName] = null;
  922. this._engine.setIntArray3(this.getUniform(uniformName), array);
  923. return this;
  924. };
  925. /**
  926. * 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)
  927. * @param uniformName Name of the variable.
  928. * @param array array to be set.
  929. * @returns this effect.
  930. */
  931. Effect.prototype.setIntArray4 = function (uniformName, array) {
  932. this._valueCache[uniformName] = null;
  933. this._engine.setIntArray4(this.getUniform(uniformName), array);
  934. return this;
  935. };
  936. /**
  937. * Sets an float array on a uniform variable.
  938. * @param uniformName Name of the variable.
  939. * @param array array to be set.
  940. * @returns this effect.
  941. */
  942. Effect.prototype.setFloatArray = function (uniformName, array) {
  943. this._valueCache[uniformName] = null;
  944. this._engine.setFloatArray(this.getUniform(uniformName), array);
  945. return this;
  946. };
  947. /**
  948. * 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)
  949. * @param uniformName Name of the variable.
  950. * @param array array to be set.
  951. * @returns this effect.
  952. */
  953. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  954. this._valueCache[uniformName] = null;
  955. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  956. return this;
  957. };
  958. /**
  959. * 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)
  960. * @param uniformName Name of the variable.
  961. * @param array array to be set.
  962. * @returns this effect.
  963. */
  964. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  965. this._valueCache[uniformName] = null;
  966. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  967. return this;
  968. };
  969. /**
  970. * 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)
  971. * @param uniformName Name of the variable.
  972. * @param array array to be set.
  973. * @returns this effect.
  974. */
  975. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  976. this._valueCache[uniformName] = null;
  977. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  978. return this;
  979. };
  980. /**
  981. * Sets an array on a uniform variable.
  982. * @param uniformName Name of the variable.
  983. * @param array array to be set.
  984. * @returns this effect.
  985. */
  986. Effect.prototype.setArray = function (uniformName, array) {
  987. this._valueCache[uniformName] = null;
  988. this._engine.setArray(this.getUniform(uniformName), array);
  989. return this;
  990. };
  991. /**
  992. * 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)
  993. * @param uniformName Name of the variable.
  994. * @param array array to be set.
  995. * @returns this effect.
  996. */
  997. Effect.prototype.setArray2 = function (uniformName, array) {
  998. this._valueCache[uniformName] = null;
  999. this._engine.setArray2(this.getUniform(uniformName), array);
  1000. return this;
  1001. };
  1002. /**
  1003. * 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)
  1004. * @param uniformName Name of the variable.
  1005. * @param array array to be set.
  1006. * @returns this effect.
  1007. */
  1008. Effect.prototype.setArray3 = function (uniformName, array) {
  1009. this._valueCache[uniformName] = null;
  1010. this._engine.setArray3(this.getUniform(uniformName), array);
  1011. return this;
  1012. };
  1013. /**
  1014. * 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)
  1015. * @param uniformName Name of the variable.
  1016. * @param array array to be set.
  1017. * @returns this effect.
  1018. */
  1019. Effect.prototype.setArray4 = function (uniformName, array) {
  1020. this._valueCache[uniformName] = null;
  1021. this._engine.setArray4(this.getUniform(uniformName), array);
  1022. return this;
  1023. };
  1024. /**
  1025. * Sets matrices on a uniform variable.
  1026. * @param uniformName Name of the variable.
  1027. * @param matrices matrices to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1031. if (!matrices) {
  1032. return this;
  1033. }
  1034. this._valueCache[uniformName] = null;
  1035. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets matrix on a uniform variable.
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1045. if (this._cacheMatrix(uniformName, matrix)) {
  1046. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1047. }
  1048. return this;
  1049. };
  1050. /**
  1051. * 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)
  1052. * @param uniformName Name of the variable.
  1053. * @param matrix matrix to be set.
  1054. * @returns this effect.
  1055. */
  1056. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1057. this._valueCache[uniformName] = null;
  1058. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1059. return this;
  1060. };
  1061. /**
  1062. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1063. * @param uniformName Name of the variable.
  1064. * @param matrix matrix to be set.
  1065. * @returns this effect.
  1066. */
  1067. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1068. this._valueCache[uniformName] = null;
  1069. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1070. return this;
  1071. };
  1072. /**
  1073. * Sets a float on a uniform variable.
  1074. * @param uniformName Name of the variable.
  1075. * @param value value to be set.
  1076. * @returns this effect.
  1077. */
  1078. Effect.prototype.setFloat = function (uniformName, value) {
  1079. var cache = this._valueCache[uniformName];
  1080. if (cache !== undefined && cache === value)
  1081. return this;
  1082. this._valueCache[uniformName] = value;
  1083. this._engine.setFloat(this.getUniform(uniformName), value);
  1084. return this;
  1085. };
  1086. /**
  1087. * Sets a boolean on a uniform variable.
  1088. * @param uniformName Name of the variable.
  1089. * @param bool value to be set.
  1090. * @returns this effect.
  1091. */
  1092. Effect.prototype.setBool = function (uniformName, bool) {
  1093. var cache = this._valueCache[uniformName];
  1094. if (cache !== undefined && cache === bool)
  1095. return this;
  1096. this._valueCache[uniformName] = bool;
  1097. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a Vector2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param vector2 vector2 to be set.
  1104. * @returns this effect.
  1105. */
  1106. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1107. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1108. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1109. }
  1110. return this;
  1111. };
  1112. /**
  1113. * Sets a float2 on a uniform variable.
  1114. * @param uniformName Name of the variable.
  1115. * @param x First float in float2.
  1116. * @param y Second float in float2.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1120. if (this._cacheFloat2(uniformName, x, y)) {
  1121. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a Vector3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param vector3 Value to be set.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1132. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1133. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a float3 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param x First float in float3.
  1141. * @param y Second float in float3.
  1142. * @param z Third float in float3.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1146. if (this._cacheFloat3(uniformName, x, y, z)) {
  1147. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a Vector4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param vector4 Value to be set.
  1155. * @returns this effect.
  1156. */
  1157. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1158. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1159. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1160. }
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a float4 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param x First float in float4.
  1167. * @param y Second float in float4.
  1168. * @param z Third float in float4.
  1169. * @param w Fourth float in float4.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1173. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color3 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @returns this effect.
  1183. */
  1184. Effect.prototype.setColor3 = function (uniformName, color3) {
  1185. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1186. this._engine.setColor3(this.getUniform(uniformName), color3);
  1187. }
  1188. return this;
  1189. };
  1190. /**
  1191. * Sets a Color4 on a uniform variable.
  1192. * @param uniformName Name of the variable.
  1193. * @param color3 Value to be set.
  1194. * @param alpha Alpha value to be set.
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1198. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1199. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * Sets a Color4 on a uniform variable
  1205. * @param uniformName defines the name of the variable
  1206. * @param color4 defines the value to be set
  1207. * @returns this effect.
  1208. */
  1209. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1210. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1211. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1212. }
  1213. return this;
  1214. };
  1215. /**
  1216. * Resets the cache of effects.
  1217. */
  1218. Effect.ResetCache = function () {
  1219. Effect._baseCache = {};
  1220. };
  1221. Effect._uniqueIdSeed = 0;
  1222. Effect._baseCache = {};
  1223. /**
  1224. * Store of each shader (The can be looked up using effect.key)
  1225. */
  1226. Effect.ShadersStore = {};
  1227. /**
  1228. * Store of each included file for a shader (The can be looked up using effect.key)
  1229. */
  1230. Effect.IncludesShadersStore = {};
  1231. return Effect;
  1232. }());
  1233. BABYLON.Effect = Effect;
  1234. })(BABYLON || (BABYLON = {}));
  1235. //# sourceMappingURL=babylon.effect.js.map
  1236. //# sourceMappingURL=babylon.types.js.map
  1237. var BABYLON;
  1238. (function (BABYLON) {
  1239. var KeyboardEventTypes = /** @class */ (function () {
  1240. function KeyboardEventTypes() {
  1241. }
  1242. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1243. get: function () {
  1244. return KeyboardEventTypes._KEYDOWN;
  1245. },
  1246. enumerable: true,
  1247. configurable: true
  1248. });
  1249. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1250. get: function () {
  1251. return KeyboardEventTypes._KEYUP;
  1252. },
  1253. enumerable: true,
  1254. configurable: true
  1255. });
  1256. KeyboardEventTypes._KEYDOWN = 0x01;
  1257. KeyboardEventTypes._KEYUP = 0x02;
  1258. return KeyboardEventTypes;
  1259. }());
  1260. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. function KeyboardInfo(type, event) {
  1263. this.type = type;
  1264. this.event = event;
  1265. }
  1266. return KeyboardInfo;
  1267. }());
  1268. BABYLON.KeyboardInfo = KeyboardInfo;
  1269. /**
  1270. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1271. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1272. */
  1273. var KeyboardInfoPre = /** @class */ (function (_super) {
  1274. __extends(KeyboardInfoPre, _super);
  1275. function KeyboardInfoPre(type, event) {
  1276. var _this = _super.call(this, type, event) || this;
  1277. _this.skipOnPointerObservable = false;
  1278. return _this;
  1279. }
  1280. return KeyboardInfoPre;
  1281. }(KeyboardInfo));
  1282. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1283. })(BABYLON || (BABYLON = {}));
  1284. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1285. var BABYLON;
  1286. (function (BABYLON) {
  1287. var PointerEventTypes = /** @class */ (function () {
  1288. function PointerEventTypes() {
  1289. }
  1290. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1291. get: function () {
  1292. return PointerEventTypes._POINTERDOWN;
  1293. },
  1294. enumerable: true,
  1295. configurable: true
  1296. });
  1297. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1298. get: function () {
  1299. return PointerEventTypes._POINTERUP;
  1300. },
  1301. enumerable: true,
  1302. configurable: true
  1303. });
  1304. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1305. get: function () {
  1306. return PointerEventTypes._POINTERMOVE;
  1307. },
  1308. enumerable: true,
  1309. configurable: true
  1310. });
  1311. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1312. get: function () {
  1313. return PointerEventTypes._POINTERWHEEL;
  1314. },
  1315. enumerable: true,
  1316. configurable: true
  1317. });
  1318. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1319. get: function () {
  1320. return PointerEventTypes._POINTERPICK;
  1321. },
  1322. enumerable: true,
  1323. configurable: true
  1324. });
  1325. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1326. get: function () {
  1327. return PointerEventTypes._POINTERTAP;
  1328. },
  1329. enumerable: true,
  1330. configurable: true
  1331. });
  1332. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1333. get: function () {
  1334. return PointerEventTypes._POINTERDOUBLETAP;
  1335. },
  1336. enumerable: true,
  1337. configurable: true
  1338. });
  1339. PointerEventTypes._POINTERDOWN = 0x01;
  1340. PointerEventTypes._POINTERUP = 0x02;
  1341. PointerEventTypes._POINTERMOVE = 0x04;
  1342. PointerEventTypes._POINTERWHEEL = 0x08;
  1343. PointerEventTypes._POINTERPICK = 0x10;
  1344. PointerEventTypes._POINTERTAP = 0x20;
  1345. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1346. return PointerEventTypes;
  1347. }());
  1348. BABYLON.PointerEventTypes = PointerEventTypes;
  1349. var PointerInfoBase = /** @class */ (function () {
  1350. function PointerInfoBase(type, event) {
  1351. this.type = type;
  1352. this.event = event;
  1353. }
  1354. return PointerInfoBase;
  1355. }());
  1356. BABYLON.PointerInfoBase = PointerInfoBase;
  1357. /**
  1358. * This class is used to store pointer related info for the onPrePointerObservable event.
  1359. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1360. */
  1361. var PointerInfoPre = /** @class */ (function (_super) {
  1362. __extends(PointerInfoPre, _super);
  1363. function PointerInfoPre(type, event, localX, localY) {
  1364. var _this = _super.call(this, type, event) || this;
  1365. _this.skipOnPointerObservable = false;
  1366. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1367. return _this;
  1368. }
  1369. return PointerInfoPre;
  1370. }(PointerInfoBase));
  1371. BABYLON.PointerInfoPre = PointerInfoPre;
  1372. /**
  1373. * This type contains all the data related to a pointer event in Babylon.js.
  1374. * 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.
  1375. */
  1376. var PointerInfo = /** @class */ (function (_super) {
  1377. __extends(PointerInfo, _super);
  1378. function PointerInfo(type, event, pickInfo) {
  1379. var _this = _super.call(this, type, event) || this;
  1380. _this.pickInfo = pickInfo;
  1381. return _this;
  1382. }
  1383. return PointerInfo;
  1384. }(PointerInfoBase));
  1385. BABYLON.PointerInfo = PointerInfo;
  1386. })(BABYLON || (BABYLON = {}));
  1387. //# sourceMappingURL=babylon.pointerEvents.js.map
  1388. var BABYLON;
  1389. (function (BABYLON) {
  1390. BABYLON.ToGammaSpace = 1 / 2.2;
  1391. BABYLON.ToLinearSpace = 2.2;
  1392. BABYLON.Epsilon = 0.001;
  1393. /**
  1394. * Class used to hold a RBG color
  1395. */
  1396. var Color3 = /** @class */ (function () {
  1397. /**
  1398. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1399. * @param r defines the red component (between 0 and 1, default is 0)
  1400. * @param g defines the green component (between 0 and 1, default is 0)
  1401. * @param b defines the blue component (between 0 and 1, default is 0)
  1402. */
  1403. function Color3(
  1404. /**
  1405. * Defines the red component (between 0 and 1, default is 0)
  1406. */
  1407. r,
  1408. /**
  1409. * Defines the green component (between 0 and 1, default is 0)
  1410. */
  1411. g,
  1412. /**
  1413. * Defines the blue component (between 0 and 1, default is 0)
  1414. */
  1415. b) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. this.r = r;
  1420. this.g = g;
  1421. this.b = b;
  1422. }
  1423. /**
  1424. * Creates a string with the Color3 current values
  1425. * @returns the string representation of the Color3 object
  1426. */
  1427. Color3.prototype.toString = function () {
  1428. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1429. };
  1430. /**
  1431. * Returns the string "Color3"
  1432. * @returns "Color3"
  1433. */
  1434. Color3.prototype.getClassName = function () {
  1435. return "Color3";
  1436. };
  1437. /**
  1438. * Compute the Color3 hash code
  1439. * @returns an unique number that can be used to hash Color3 objects
  1440. */
  1441. Color3.prototype.getHashCode = function () {
  1442. var hash = this.r || 0;
  1443. hash = (hash * 397) ^ (this.g || 0);
  1444. hash = (hash * 397) ^ (this.b || 0);
  1445. return hash;
  1446. };
  1447. // Operators
  1448. /**
  1449. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1450. * @param array defines the array where to store the r,g,b components
  1451. * @param index defines an optional index in the target array to define where to start storing values
  1452. * @returns the current Color3 object
  1453. */
  1454. Color3.prototype.toArray = function (array, index) {
  1455. if (index === undefined) {
  1456. index = 0;
  1457. }
  1458. array[index] = this.r;
  1459. array[index + 1] = this.g;
  1460. array[index + 2] = this.b;
  1461. return this;
  1462. };
  1463. /**
  1464. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1465. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1466. * @returns a new {BABYLON.Color4} object
  1467. */
  1468. Color3.prototype.toColor4 = function (alpha) {
  1469. if (alpha === void 0) { alpha = 1; }
  1470. return new Color4(this.r, this.g, this.b, alpha);
  1471. };
  1472. /**
  1473. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1474. * @returns the new array
  1475. */
  1476. Color3.prototype.asArray = function () {
  1477. var result = new Array();
  1478. this.toArray(result, 0);
  1479. return result;
  1480. };
  1481. /**
  1482. * Returns the luminance value
  1483. * @returns a float value
  1484. */
  1485. Color3.prototype.toLuminance = function () {
  1486. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1487. };
  1488. /**
  1489. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1490. * @param otherColor defines the second operand
  1491. * @returns the new Color3 object
  1492. */
  1493. Color3.prototype.multiply = function (otherColor) {
  1494. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1495. };
  1496. /**
  1497. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1498. * @param otherColor defines the second operand
  1499. * @param result defines the Color3 object where to store the result
  1500. * @returns the current Color3
  1501. */
  1502. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1503. result.r = this.r * otherColor.r;
  1504. result.g = this.g * otherColor.g;
  1505. result.b = this.b * otherColor.b;
  1506. return this;
  1507. };
  1508. /**
  1509. * Determines equality between Color3 objects
  1510. * @param otherColor defines the second operand
  1511. * @returns true if the rgb values are equal to the given ones
  1512. */
  1513. Color3.prototype.equals = function (otherColor) {
  1514. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1515. };
  1516. /**
  1517. * Determines equality between the current Color3 object and a set of r,b,g values
  1518. * @param r defines the red component to check
  1519. * @param g defines the green component to check
  1520. * @param b defines the blue component to check
  1521. * @returns true if the rgb values are equal to the given ones
  1522. */
  1523. Color3.prototype.equalsFloats = function (r, g, b) {
  1524. return this.r === r && this.g === g && this.b === b;
  1525. };
  1526. /**
  1527. * Multiplies in place each rgb value by scale
  1528. * @param scale defines the scaling factor
  1529. * @returns the updated Color3
  1530. */
  1531. Color3.prototype.scale = function (scale) {
  1532. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1533. };
  1534. /**
  1535. * Multiplies the rgb values by scale and stores the result into "result"
  1536. * @param scale defines the scaling factor
  1537. * @param result defines the Color3 object where to store the result
  1538. * @returns the unmodified current Color3
  1539. */
  1540. Color3.prototype.scaleToRef = function (scale, result) {
  1541. result.r = this.r * scale;
  1542. result.g = this.g * scale;
  1543. result.b = this.b * scale;
  1544. return this;
  1545. };
  1546. /**
  1547. * Scale the current Color3 values by a factor and add the result to a given Color3
  1548. * @param scale defines the scale factor
  1549. * @param result defines color to store the result into
  1550. * @returns the unmodified current Color3
  1551. */
  1552. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1553. result.r += this.r * scale;
  1554. result.g += this.g * scale;
  1555. result.b += this.b * scale;
  1556. return this;
  1557. };
  1558. /**
  1559. * Clamps the rgb values by the min and max values and stores the result into "result"
  1560. * @param min defines minimum clamping value (default is 0)
  1561. * @param max defines maximum clamping value (default is 1)
  1562. * @param result defines color to store the result into
  1563. * @returns the original Color3
  1564. */
  1565. Color3.prototype.clampToRef = function (min, max, result) {
  1566. if (min === void 0) { min = 0; }
  1567. if (max === void 0) { max = 1; }
  1568. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1569. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1570. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1571. return this;
  1572. };
  1573. /**
  1574. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.add = function (otherColor) {
  1579. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.addToRef = function (otherColor, result) {
  1588. result.r = this.r + otherColor.r;
  1589. result.g = this.g + otherColor.g;
  1590. result.b = this.b + otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1595. * @param otherColor defines the second operand
  1596. * @returns the new Color3
  1597. */
  1598. Color3.prototype.subtract = function (otherColor) {
  1599. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1600. };
  1601. /**
  1602. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1603. * @param otherColor defines the second operand
  1604. * @param result defines Color3 object to store the result into
  1605. * @returns the unmodified current Color3
  1606. */
  1607. Color3.prototype.subtractToRef = function (otherColor, result) {
  1608. result.r = this.r - otherColor.r;
  1609. result.g = this.g - otherColor.g;
  1610. result.b = this.b - otherColor.b;
  1611. return this;
  1612. };
  1613. /**
  1614. * Copy the current object
  1615. * @returns a new Color3 copied the current one
  1616. */
  1617. Color3.prototype.clone = function () {
  1618. return new Color3(this.r, this.g, this.b);
  1619. };
  1620. /**
  1621. * Copies the rgb values from the source in the current Color3
  1622. * @param source defines the source Color3 object
  1623. * @returns the updated Color3 object
  1624. */
  1625. Color3.prototype.copyFrom = function (source) {
  1626. this.r = source.r;
  1627. this.g = source.g;
  1628. this.b = source.b;
  1629. return this;
  1630. };
  1631. /**
  1632. * Updates the Color3 rgb values from the given floats
  1633. * @param r defines the red component to read from
  1634. * @param g defines the green component to read from
  1635. * @param b defines the blue component to read from
  1636. * @returns the current Color3 object
  1637. */
  1638. Color3.prototype.copyFromFloats = function (r, g, b) {
  1639. this.r = r;
  1640. this.g = g;
  1641. this.b = b;
  1642. return this;
  1643. };
  1644. /**
  1645. * Updates the Color3 rgb values from the given 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.set = function (r, g, b) {
  1652. return this.copyFromFloats(r, g, b);
  1653. };
  1654. /**
  1655. * Compute the Color3 hexadecimal code as a string
  1656. * @returns a string containing the hexadecimal representation of the Color3 object
  1657. */
  1658. Color3.prototype.toHexString = function () {
  1659. var intR = (this.r * 255) | 0;
  1660. var intG = (this.g * 255) | 0;
  1661. var intB = (this.b * 255) | 0;
  1662. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to linear space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toLinearSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toLinearSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the linear space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1682. return this;
  1683. };
  1684. /**
  1685. * Computes a new Color3 converted from the current one to gamma space
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.prototype.toGammaSpace = function () {
  1689. var convertedColor = new Color3();
  1690. this.toGammaSpaceToRef(convertedColor);
  1691. return convertedColor;
  1692. };
  1693. /**
  1694. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1695. * @param convertedColor defines the Color3 object where to store the gamma space version
  1696. * @returns the unmodified Color3
  1697. */
  1698. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1699. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1700. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1701. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1702. return this;
  1703. };
  1704. // Statics
  1705. /**
  1706. * Creates a new Color3 from the string containing valid hexadecimal values
  1707. * @param hex defines a string containing valid hexadecimal values
  1708. * @returns a new Color3 object
  1709. */
  1710. Color3.FromHexString = function (hex) {
  1711. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1712. return new Color3(0, 0, 0);
  1713. }
  1714. var r = parseInt(hex.substring(1, 3), 16);
  1715. var g = parseInt(hex.substring(3, 5), 16);
  1716. var b = parseInt(hex.substring(5, 7), 16);
  1717. return Color3.FromInts(r, g, b);
  1718. };
  1719. /**
  1720. * Creates a new Vector3 from the starting index of the given array
  1721. * @param array defines the source array
  1722. * @param offset defines an offset in the source array
  1723. * @returns a new Color3 object
  1724. */
  1725. Color3.FromArray = function (array, offset) {
  1726. if (offset === void 0) { offset = 0; }
  1727. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1728. };
  1729. /**
  1730. * Creates a new Color3 from integer values (< 256)
  1731. * @param r defines the red component to read from (value between 0 and 255)
  1732. * @param g defines the green component to read from (value between 0 and 255)
  1733. * @param b defines the blue component to read from (value between 0 and 255)
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.FromInts = function (r, g, b) {
  1737. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1738. };
  1739. /**
  1740. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1741. * @param start defines the start Color3 value
  1742. * @param end defines the end Color3 value
  1743. * @param amount defines the gradient value between start and end
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Lerp = function (start, end, amount) {
  1747. var r = start.r + ((end.r - start.r) * amount);
  1748. var g = start.g + ((end.g - start.g) * amount);
  1749. var b = start.b + ((end.b - start.b) * amount);
  1750. return new Color3(r, g, b);
  1751. };
  1752. /**
  1753. * Returns a Color3 value containing a red color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.Red = function () { return new Color3(1, 0, 0); };
  1757. /**
  1758. * Returns a Color3 value containing a green color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Green = function () { return new Color3(0, 1, 0); };
  1762. /**
  1763. * Returns a Color3 value containing a blue color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a black color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Black = function () { return new Color3(0, 0, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a white color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.White = function () { return new Color3(1, 1, 1); };
  1777. /**
  1778. * Returns a Color3 value containing a purple color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1782. /**
  1783. * Returns a Color3 value containing a magenta color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1787. /**
  1788. * Returns a Color3 value containing a yellow color
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1792. /**
  1793. * Returns a Color3 value containing a gray color
  1794. * @returns a new Color3 object
  1795. */
  1796. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1797. /**
  1798. * Returns a Color3 value containing a teal color
  1799. * @returns a new Color3 object
  1800. */
  1801. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1802. /**
  1803. * Returns a Color3 value containing a random color
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1807. return Color3;
  1808. }());
  1809. BABYLON.Color3 = Color3;
  1810. /**
  1811. * Class used to hold a RBGA color
  1812. */
  1813. var Color4 = /** @class */ (function () {
  1814. /**
  1815. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1816. * @param r defines the red component (between 0 and 1, default is 0)
  1817. * @param g defines the green component (between 0 and 1, default is 0)
  1818. * @param b defines the blue component (between 0 and 1, default is 0)
  1819. * @param a defines the alpha component (between 0 and 1, default is 1)
  1820. */
  1821. function Color4(
  1822. /**
  1823. * Defines the red component (between 0 and 1, default is 0)
  1824. */
  1825. r,
  1826. /**
  1827. * Defines the green component (between 0 and 1, default is 0)
  1828. */
  1829. g,
  1830. /**
  1831. * Defines the blue component (between 0 and 1, default is 0)
  1832. */
  1833. b,
  1834. /**
  1835. * Defines the alpha component (between 0 and 1, default is 1)
  1836. */
  1837. a) {
  1838. if (r === void 0) { r = 0; }
  1839. if (g === void 0) { g = 0; }
  1840. if (b === void 0) { b = 0; }
  1841. if (a === void 0) { a = 1; }
  1842. this.r = r;
  1843. this.g = g;
  1844. this.b = b;
  1845. this.a = a;
  1846. }
  1847. // Operators
  1848. /**
  1849. * Adds in place the given Color4 values to the current Color4 object
  1850. * @param right defines the second operand
  1851. * @returns the current updated Color4 object
  1852. */
  1853. Color4.prototype.addInPlace = function (right) {
  1854. this.r += right.r;
  1855. this.g += right.g;
  1856. this.b += right.b;
  1857. this.a += right.a;
  1858. return this;
  1859. };
  1860. /**
  1861. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1862. * @returns the new array
  1863. */
  1864. Color4.prototype.asArray = function () {
  1865. var result = new Array();
  1866. this.toArray(result, 0);
  1867. return result;
  1868. };
  1869. /**
  1870. * Stores from the starting index in the given array the Color4 successive values
  1871. * @param array defines the array where to store the r,g,b components
  1872. * @param index defines an optional index in the target array to define where to start storing values
  1873. * @returns the current Color4 object
  1874. */
  1875. Color4.prototype.toArray = function (array, index) {
  1876. if (index === undefined) {
  1877. index = 0;
  1878. }
  1879. array[index] = this.r;
  1880. array[index + 1] = this.g;
  1881. array[index + 2] = this.b;
  1882. array[index + 3] = this.a;
  1883. return this;
  1884. };
  1885. /**
  1886. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1887. * @param right defines the second operand
  1888. * @returns a new Color4 object
  1889. */
  1890. Color4.prototype.add = function (right) {
  1891. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1892. };
  1893. /**
  1894. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1895. * @param right defines the second operand
  1896. * @returns a new Color4 object
  1897. */
  1898. Color4.prototype.subtract = function (right) {
  1899. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1900. };
  1901. /**
  1902. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1903. * @param right defines the second operand
  1904. * @param result defines the Color4 object where to store the result
  1905. * @returns the current Color4 object
  1906. */
  1907. Color4.prototype.subtractToRef = function (right, result) {
  1908. result.r = this.r - right.r;
  1909. result.g = this.g - right.g;
  1910. result.b = this.b - right.b;
  1911. result.a = this.a - right.a;
  1912. return this;
  1913. };
  1914. /**
  1915. * Creates a new Color4 with the current Color4 values multiplied by scale
  1916. * @param scale defines the scaling factor to apply
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.scale = function (scale) {
  1920. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1921. };
  1922. /**
  1923. * Multiplies the current Color4 values by scale and stores the result in "result"
  1924. * @param scale defines the scaling factor to apply
  1925. * @param result defines the Color4 object where to store the result
  1926. * @returns the current unmodified Color4
  1927. */
  1928. Color4.prototype.scaleToRef = function (scale, result) {
  1929. result.r = this.r * scale;
  1930. result.g = this.g * scale;
  1931. result.b = this.b * scale;
  1932. result.a = this.a * scale;
  1933. return this;
  1934. };
  1935. /**
  1936. * Scale the current Color4 values by a factor and add the result to a given Color4
  1937. * @param scale defines the scale factor
  1938. * @param result defines the Color4 object where to store the result
  1939. * @returns the unmodified current Color4
  1940. */
  1941. Color4.prototype.scaleAndAddToRef = 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 given 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 given 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 given 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 given "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 given 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. /**
  2196. * Class representing a vector containing 2 coordinates
  2197. */
  2198. var Vector2 = /** @class */ (function () {
  2199. /**
  2200. * Creates a new Vector2 from the given x and y coordinates
  2201. * @param x defines the first coordinate
  2202. * @param y defines the second coordinate
  2203. */
  2204. function Vector2(
  2205. /** defines the first coordinate */
  2206. x,
  2207. /** defines the second coordinate */
  2208. y) {
  2209. this.x = x;
  2210. this.y = y;
  2211. }
  2212. /**
  2213. * Gets a string with the Vector2 coordinates
  2214. * @returns a string with the Vector2 coordinates
  2215. */
  2216. Vector2.prototype.toString = function () {
  2217. return "{X: " + this.x + " Y:" + this.y + "}";
  2218. };
  2219. /**
  2220. * Gets class name
  2221. * @returns the string "Vector2"
  2222. */
  2223. Vector2.prototype.getClassName = function () {
  2224. return "Vector2";
  2225. };
  2226. /**
  2227. * Gets current vector hash code
  2228. * @returns the Vector2 hash code as a number
  2229. */
  2230. Vector2.prototype.getHashCode = function () {
  2231. var hash = this.x || 0;
  2232. hash = (hash * 397) ^ (this.y || 0);
  2233. return hash;
  2234. };
  2235. // Operators
  2236. /**
  2237. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2238. * @param array defines the source array
  2239. * @param index defines the offset in source array
  2240. * @returns the current Vector2
  2241. */
  2242. Vector2.prototype.toArray = function (array, index) {
  2243. if (index === void 0) { index = 0; }
  2244. array[index] = this.x;
  2245. array[index + 1] = this.y;
  2246. return this;
  2247. };
  2248. /**
  2249. * Copy the current vector to an array
  2250. * @returns a new array with 2 elements: the Vector2 coordinates.
  2251. */
  2252. Vector2.prototype.asArray = function () {
  2253. var result = new Array();
  2254. this.toArray(result, 0);
  2255. return result;
  2256. };
  2257. /**
  2258. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2259. * @param source defines the source Vector2
  2260. * @returns the current updated Vector2
  2261. */
  2262. Vector2.prototype.copyFrom = function (source) {
  2263. this.x = source.x;
  2264. this.y = source.y;
  2265. return this;
  2266. };
  2267. /**
  2268. * Sets the Vector2 coordinates with the given floats
  2269. * @param x defines the first coordinate
  2270. * @param y defines the second coordinate
  2271. * @returns the current updated Vector2
  2272. */
  2273. Vector2.prototype.copyFromFloats = function (x, y) {
  2274. this.x = x;
  2275. this.y = y;
  2276. return this;
  2277. };
  2278. /**
  2279. * Sets the Vector2 coordinates with the given floats
  2280. * @param x defines the first coordinate
  2281. * @param y defines the second coordinate
  2282. * @returns the current updated Vector2
  2283. */
  2284. Vector2.prototype.set = function (x, y) {
  2285. return this.copyFromFloats(x, y);
  2286. };
  2287. /**
  2288. * Add another vector with the current one
  2289. * @param otherVector defines the other vector
  2290. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2291. */
  2292. Vector2.prototype.add = function (otherVector) {
  2293. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2294. };
  2295. /**
  2296. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2297. * @param otherVector defines the other vector
  2298. * @param result defines the target vector
  2299. * @returns the unmodified current Vector2
  2300. */
  2301. Vector2.prototype.addToRef = function (otherVector, result) {
  2302. result.x = this.x + otherVector.x;
  2303. result.y = this.y + otherVector.y;
  2304. return this;
  2305. };
  2306. /**
  2307. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2308. * @param otherVector defines the other vector
  2309. * @returns the current updated Vector2
  2310. */
  2311. Vector2.prototype.addInPlace = function (otherVector) {
  2312. this.x += otherVector.x;
  2313. this.y += otherVector.y;
  2314. return this;
  2315. };
  2316. /**
  2317. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2318. * @param otherVector defines the other vector
  2319. * @returns a new Vector2
  2320. */
  2321. Vector2.prototype.addVector3 = function (otherVector) {
  2322. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2323. };
  2324. /**
  2325. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2326. * @param otherVector defines the other vector
  2327. * @returns a new Vector2
  2328. */
  2329. Vector2.prototype.subtract = function (otherVector) {
  2330. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2331. };
  2332. /**
  2333. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2334. * @param otherVector defines the other vector
  2335. * @param result defines the target vector
  2336. * @returns the unmodified current Vector2
  2337. */
  2338. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2339. result.x = this.x - otherVector.x;
  2340. result.y = this.y - otherVector.y;
  2341. return this;
  2342. };
  2343. /**
  2344. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2345. * @param otherVector defines the other vector
  2346. * @returns the current updated Vector2
  2347. */
  2348. Vector2.prototype.subtractInPlace = function (otherVector) {
  2349. this.x -= otherVector.x;
  2350. this.y -= otherVector.y;
  2351. return this;
  2352. };
  2353. /**
  2354. * Multiplies in place the current Vector2 coordinates by the given ones
  2355. * @param otherVector defines the other vector
  2356. * @returns the current updated Vector2
  2357. */
  2358. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2359. this.x *= otherVector.x;
  2360. this.y *= otherVector.y;
  2361. return this;
  2362. };
  2363. /**
  2364. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2365. * @param otherVector defines the other vector
  2366. * @returns a new Vector2
  2367. */
  2368. Vector2.prototype.multiply = function (otherVector) {
  2369. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2370. };
  2371. /**
  2372. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2373. * @param otherVector defines the other vector
  2374. * @param result defines the target vector
  2375. * @returns the unmodified current Vector2
  2376. */
  2377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2378. result.x = this.x * otherVector.x;
  2379. result.y = this.y * otherVector.y;
  2380. return this;
  2381. };
  2382. /**
  2383. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2384. * @param x defines the first coordinate
  2385. * @param y defines the second coordinate
  2386. * @returns a new Vector2
  2387. */
  2388. Vector2.prototype.multiplyByFloats = function (x, y) {
  2389. return new Vector2(this.x * x, this.y * y);
  2390. };
  2391. /**
  2392. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2393. * @param otherVector defines the other vector
  2394. * @returns a new Vector2
  2395. */
  2396. Vector2.prototype.divide = function (otherVector) {
  2397. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2398. };
  2399. /**
  2400. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @param result defines the target vector
  2403. * @returns the unmodified current Vector2
  2404. */
  2405. Vector2.prototype.divideToRef = function (otherVector, result) {
  2406. result.x = this.x / otherVector.x;
  2407. result.y = this.y / otherVector.y;
  2408. return this;
  2409. };
  2410. /**
  2411. * Divides the current Vector3 coordinates by the given ones
  2412. * @param otherVector defines the other vector
  2413. * @returns the current updated Vector2
  2414. */
  2415. Vector2.prototype.divideInPlace = function (otherVector) {
  2416. return this.divideToRef(otherVector, this);
  2417. };
  2418. /**
  2419. * Gets a new Vector2 with current Vector2 negated coordinates
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.negate = function () {
  2423. return new Vector2(-this.x, -this.y);
  2424. };
  2425. /**
  2426. * Multiply the Vector2 coordinates by scale
  2427. * @param scale defines the scaling factor
  2428. * @returns the current updated Vector2
  2429. */
  2430. Vector2.prototype.scaleInPlace = function (scale) {
  2431. this.x *= scale;
  2432. this.y *= scale;
  2433. return this;
  2434. };
  2435. /**
  2436. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2437. * @param scale defines the scaling factor
  2438. * @returns a new Vector2
  2439. */
  2440. Vector2.prototype.scale = function (scale) {
  2441. var result = new Vector2(0, 0);
  2442. this.scaleToRef(scale, result);
  2443. return result;
  2444. };
  2445. /**
  2446. * Scale the current Vector2 values by a factor to a given Vector2
  2447. * @param scale defines the scale factor
  2448. * @param result defines the Vector2 object where to store the result
  2449. * @returns the unmodified current Vector2
  2450. */
  2451. Vector2.prototype.scaleToRef = function (scale, result) {
  2452. result.x = this.x * scale;
  2453. result.y = this.y * scale;
  2454. return this;
  2455. };
  2456. /**
  2457. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2458. * @param scale defines the scale factor
  2459. * @param result defines the Vector2 object where to store the result
  2460. * @returns the unmodified current Vector2
  2461. */
  2462. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2463. result.x += this.x * scale;
  2464. result.y += this.y * scale;
  2465. return this;
  2466. };
  2467. /**
  2468. * Gets a boolean if two vectors are equals
  2469. * @param otherVector defines the other vector
  2470. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2471. */
  2472. Vector2.prototype.equals = function (otherVector) {
  2473. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2474. };
  2475. /**
  2476. * Gets a boolean if two vectors are equals (using an epsilon value)
  2477. * @param otherVector defines the other vector
  2478. * @param epsilon defines the minimal distance to consider equality
  2479. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2480. */
  2481. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2482. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2483. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2484. };
  2485. // Properties
  2486. /**
  2487. * Gets the length of the vector
  2488. * @returns the vector length (float)
  2489. */
  2490. Vector2.prototype.length = function () {
  2491. return Math.sqrt(this.x * this.x + this.y * this.y);
  2492. };
  2493. /**
  2494. * Gets the vector squared length
  2495. * @returns the vector squared length (float)
  2496. */
  2497. Vector2.prototype.lengthSquared = function () {
  2498. return (this.x * this.x + this.y * this.y);
  2499. };
  2500. // Methods
  2501. /**
  2502. * Normalize the vector
  2503. * @returns the current updated Vector2
  2504. */
  2505. Vector2.prototype.normalize = function () {
  2506. var len = this.length();
  2507. if (len === 0)
  2508. return this;
  2509. var num = 1.0 / len;
  2510. this.x *= num;
  2511. this.y *= num;
  2512. return this;
  2513. };
  2514. /**
  2515. * Gets a new Vector2 copied from the Vector2
  2516. * @returns a new Vector2
  2517. */
  2518. Vector2.prototype.clone = function () {
  2519. return new Vector2(this.x, this.y);
  2520. };
  2521. // Statics
  2522. /**
  2523. * Gets a new Vector2(0, 0)
  2524. * @returns a new Vector2
  2525. */
  2526. Vector2.Zero = function () {
  2527. return new Vector2(0, 0);
  2528. };
  2529. /**
  2530. * Gets a new Vector2(1, 1)
  2531. * @returns a new Vector2
  2532. */
  2533. Vector2.One = function () {
  2534. return new Vector2(1, 1);
  2535. };
  2536. /**
  2537. * Gets a new Vector2 set from the given index element of the given array
  2538. * @param array defines the data source
  2539. * @param offset defines the offset in the data source
  2540. * @returns a new Vector2
  2541. */
  2542. Vector2.FromArray = function (array, offset) {
  2543. if (offset === void 0) { offset = 0; }
  2544. return new Vector2(array[offset], array[offset + 1]);
  2545. };
  2546. /**
  2547. * Sets "result" from the given index element of the given array
  2548. * @param array defines the data source
  2549. * @param offset defines the offset in the data source
  2550. * @param result defines the target vector
  2551. */
  2552. Vector2.FromArrayToRef = function (array, offset, result) {
  2553. result.x = array[offset];
  2554. result.y = array[offset + 1];
  2555. };
  2556. /**
  2557. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2558. * @param value1 defines 1st point of control
  2559. * @param value2 defines 2nd point of control
  2560. * @param value3 defines 3rd point of control
  2561. * @param value4 defines 4th point of control
  2562. * @param amount defines the interpolation factor
  2563. * @returns a new Vector2
  2564. */
  2565. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2566. var squared = amount * amount;
  2567. var cubed = amount * squared;
  2568. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2569. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2570. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2571. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2572. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2573. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * 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".
  2578. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2579. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2580. * @param value defines the value to clamp
  2581. * @param min defines the lower limit
  2582. * @param max defines the upper limit
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Clamp = function (value, min, max) {
  2586. var x = value.x;
  2587. x = (x > max.x) ? max.x : x;
  2588. x = (x < min.x) ? min.x : x;
  2589. var y = value.y;
  2590. y = (y > max.y) ? max.y : y;
  2591. y = (y < min.y) ? min.y : y;
  2592. return new Vector2(x, y);
  2593. };
  2594. /**
  2595. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2596. * @param value1 defines the 1st control point
  2597. * @param tangent1 defines the outgoing tangent
  2598. * @param value2 defines the 2nd control point
  2599. * @param tangent2 defines the incoming tangent
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2604. var squared = amount * amount;
  2605. var cubed = amount * squared;
  2606. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2607. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2608. var part3 = (cubed - (2.0 * squared)) + amount;
  2609. var part4 = cubed - squared;
  2610. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2611. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2612. return new Vector2(x, y);
  2613. };
  2614. /**
  2615. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2616. * @param start defines the start vector
  2617. * @param end defines the end vector
  2618. * @param amount defines the interpolation factor
  2619. * @returns a new Vector2
  2620. */
  2621. Vector2.Lerp = function (start, end, amount) {
  2622. var x = start.x + ((end.x - start.x) * amount);
  2623. var y = start.y + ((end.y - start.y) * amount);
  2624. return new Vector2(x, y);
  2625. };
  2626. /**
  2627. * Gets the dot product of the vector "left" and the vector "right"
  2628. * @param left defines first vector
  2629. * @param right defines second vector
  2630. * @returns the dot product (float)
  2631. */
  2632. Vector2.Dot = function (left, right) {
  2633. return left.x * right.x + left.y * right.y;
  2634. };
  2635. /**
  2636. * Returns a new Vector2 equal to the normalized given vector
  2637. * @param vector defines the vector to normalize
  2638. * @returns a new Vector2
  2639. */
  2640. Vector2.Normalize = function (vector) {
  2641. var newVector = vector.clone();
  2642. newVector.normalize();
  2643. return newVector;
  2644. };
  2645. /**
  2646. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2647. * @param left defines 1st vector
  2648. * @param right defines 2nd vector
  2649. * @returns a new Vector2
  2650. */
  2651. Vector2.Minimize = function (left, right) {
  2652. var x = (left.x < right.x) ? left.x : right.x;
  2653. var y = (left.y < right.y) ? left.y : right.y;
  2654. return new Vector2(x, y);
  2655. };
  2656. /**
  2657. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2658. * @param left defines 1st vector
  2659. * @param right defines 2nd vector
  2660. * @returns a new Vector2
  2661. */
  2662. Vector2.Maximize = function (left, right) {
  2663. var x = (left.x > right.x) ? left.x : right.x;
  2664. var y = (left.y > right.y) ? left.y : right.y;
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2669. * @param vector defines the vector to transform
  2670. * @param transformation defines the matrix to apply
  2671. * @returns a new Vector2
  2672. */
  2673. Vector2.Transform = function (vector, transformation) {
  2674. var r = Vector2.Zero();
  2675. Vector2.TransformToRef(vector, transformation, r);
  2676. return r;
  2677. };
  2678. /**
  2679. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2680. * @param vector defines the vector to transform
  2681. * @param transformation defines the matrix to apply
  2682. * @param result defines the target vector
  2683. */
  2684. Vector2.TransformToRef = function (vector, transformation, result) {
  2685. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2686. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2687. result.x = x;
  2688. result.y = y;
  2689. };
  2690. /**
  2691. * Determines if a given vector is included in a triangle
  2692. * @param p defines the vector to test
  2693. * @param p0 defines 1st triangle point
  2694. * @param p1 defines 2nd triangle point
  2695. * @param p2 defines 3rd triangle point
  2696. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2697. */
  2698. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2699. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2700. var sign = a < 0 ? -1 : 1;
  2701. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2702. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2703. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2704. };
  2705. /**
  2706. * Gets the distance between the vectors "value1" and "value2"
  2707. * @param value1 defines first vector
  2708. * @param value2 defines second vector
  2709. * @returns the distance between vectors
  2710. */
  2711. Vector2.Distance = function (value1, value2) {
  2712. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2713. };
  2714. /**
  2715. * Returns the squared distance between the vectors "value1" and "value2"
  2716. * @param value1 defines first vector
  2717. * @param value2 defines second vector
  2718. * @returns the squared distance between vectors
  2719. */
  2720. Vector2.DistanceSquared = function (value1, value2) {
  2721. var x = value1.x - value2.x;
  2722. var y = value1.y - value2.y;
  2723. return (x * x) + (y * y);
  2724. };
  2725. /**
  2726. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2727. * @param value1 defines first vector
  2728. * @param value2 defines second vector
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Center = function (value1, value2) {
  2732. var center = value1.add(value2);
  2733. center.scaleInPlace(0.5);
  2734. return center;
  2735. };
  2736. /**
  2737. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2738. * @param p defines the middle point
  2739. * @param segA defines one point of the segment
  2740. * @param segB defines the other point of the segment
  2741. * @returns the shortest distance
  2742. */
  2743. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2744. var l2 = Vector2.DistanceSquared(segA, segB);
  2745. if (l2 === 0.0) {
  2746. return Vector2.Distance(p, segA);
  2747. }
  2748. var v = segB.subtract(segA);
  2749. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2750. var proj = segA.add(v.multiplyByFloats(t, t));
  2751. return Vector2.Distance(p, proj);
  2752. };
  2753. return Vector2;
  2754. }());
  2755. BABYLON.Vector2 = Vector2;
  2756. /**
  2757. * Classed used to store (x,y,z) vector representation
  2758. * A Vector3 is the main object used in 3D geometry
  2759. * It can represent etiher the coordinates of a point the space, either a direction
  2760. * Reminder: Babylon.js uses a left handed forward facing system
  2761. */
  2762. var Vector3 = /** @class */ (function () {
  2763. /**
  2764. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2765. * @param x defines the first coordinates (on X axis)
  2766. * @param y defines the second coordinates (on Y axis)
  2767. * @param z defines the third coordinates (on Z axis)
  2768. */
  2769. function Vector3(
  2770. /**
  2771. * Defines the first coordinates (on X axis)
  2772. */
  2773. x,
  2774. /**
  2775. * Defines the second coordinates (on Y axis)
  2776. */
  2777. y,
  2778. /**
  2779. * Defines the third coordinates (on Z axis)
  2780. */
  2781. z) {
  2782. this.x = x;
  2783. this.y = y;
  2784. this.z = z;
  2785. }
  2786. /**
  2787. * Creates a string representation of the Vector3
  2788. * @returns a string with the Vector3 coordinates.
  2789. */
  2790. Vector3.prototype.toString = function () {
  2791. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2792. };
  2793. /**
  2794. * Gets the class name
  2795. * @returns the string "Vector3"
  2796. */
  2797. Vector3.prototype.getClassName = function () {
  2798. return "Vector3";
  2799. };
  2800. /**
  2801. * Creates the Vector3 hash code
  2802. * @returns a number which tends to be unique between Vector3 instances
  2803. */
  2804. Vector3.prototype.getHashCode = function () {
  2805. var hash = this.x || 0;
  2806. hash = (hash * 397) ^ (this.y || 0);
  2807. hash = (hash * 397) ^ (this.z || 0);
  2808. return hash;
  2809. };
  2810. // Operators
  2811. /**
  2812. * Creates an array containing three elements : the coordinates of the Vector3
  2813. * @returns a new array of numbers
  2814. */
  2815. Vector3.prototype.asArray = function () {
  2816. var result = [];
  2817. this.toArray(result, 0);
  2818. return result;
  2819. };
  2820. /**
  2821. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2822. * @param array defines the destination array
  2823. * @param index defines the offset in the destination array
  2824. * @returns the current Vector3
  2825. */
  2826. Vector3.prototype.toArray = function (array, index) {
  2827. if (index === void 0) { index = 0; }
  2828. array[index] = this.x;
  2829. array[index + 1] = this.y;
  2830. array[index + 2] = this.z;
  2831. return this;
  2832. };
  2833. /**
  2834. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2835. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2836. */
  2837. Vector3.prototype.toQuaternion = function () {
  2838. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2839. };
  2840. /**
  2841. * Adds the given vector to the current Vector3
  2842. * @param otherVector defines the second operand
  2843. * @returns the current updated Vector3
  2844. */
  2845. Vector3.prototype.addInPlace = function (otherVector) {
  2846. this.x += otherVector.x;
  2847. this.y += otherVector.y;
  2848. this.z += otherVector.z;
  2849. return this;
  2850. };
  2851. /**
  2852. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2853. * @param otherVector defines the second operand
  2854. * @returns the resulting Vector3
  2855. */
  2856. Vector3.prototype.add = function (otherVector) {
  2857. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2858. };
  2859. /**
  2860. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2861. * @param otherVector defines the second operand
  2862. * @param result defines the Vector3 object where to store the result
  2863. * @returns the current Vector3
  2864. */
  2865. Vector3.prototype.addToRef = function (otherVector, result) {
  2866. result.x = this.x + otherVector.x;
  2867. result.y = this.y + otherVector.y;
  2868. result.z = this.z + otherVector.z;
  2869. return this;
  2870. };
  2871. /**
  2872. * Subtract the given vector from the current Vector3
  2873. * @param otherVector defines the second operand
  2874. * @returns the current updated Vector3
  2875. */
  2876. Vector3.prototype.subtractInPlace = function (otherVector) {
  2877. this.x -= otherVector.x;
  2878. this.y -= otherVector.y;
  2879. this.z -= otherVector.z;
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2884. * @param otherVector defines the second operand
  2885. * @returns the resulting Vector3
  2886. */
  2887. Vector3.prototype.subtract = function (otherVector) {
  2888. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2889. };
  2890. /**
  2891. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2892. * @param otherVector defines the second operand
  2893. * @param result defines the Vector3 object where to store the result
  2894. * @returns the current Vector3
  2895. */
  2896. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2897. result.x = this.x - otherVector.x;
  2898. result.y = this.y - otherVector.y;
  2899. result.z = this.z - otherVector.z;
  2900. return this;
  2901. };
  2902. /**
  2903. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2904. * @param x defines the x coordinate of the operand
  2905. * @param y defines the y coordinate of the operand
  2906. * @param z defines the z coordinate of the operand
  2907. * @returns the resulting Vector3
  2908. */
  2909. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2910. return new Vector3(this.x - x, this.y - y, this.z - z);
  2911. };
  2912. /**
  2913. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2914. * @param x defines the x coordinate of the operand
  2915. * @param y defines the y coordinate of the operand
  2916. * @param z defines the z coordinate of the operand
  2917. * @param result defines the Vector3 object where to store the result
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2921. result.x = this.x - x;
  2922. result.y = this.y - y;
  2923. result.z = this.z - z;
  2924. return this;
  2925. };
  2926. /**
  2927. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2928. * @returns a new Vector3
  2929. */
  2930. Vector3.prototype.negate = function () {
  2931. return new Vector3(-this.x, -this.y, -this.z);
  2932. };
  2933. /**
  2934. * Multiplies the Vector3 coordinates by the float "scale"
  2935. * @param scale defines the multiplier factor
  2936. * @returns the current updated Vector3
  2937. */
  2938. Vector3.prototype.scaleInPlace = function (scale) {
  2939. this.x *= scale;
  2940. this.y *= scale;
  2941. this.z *= scale;
  2942. return this;
  2943. };
  2944. /**
  2945. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2946. * @param scale defines the multiplier factor
  2947. * @returns a new Vector3
  2948. */
  2949. Vector3.prototype.scale = function (scale) {
  2950. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2951. };
  2952. /**
  2953. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2954. * @param scale defines the multiplier factor
  2955. * @param result defines the Vector3 object where to store the result
  2956. * @returns the current Vector3
  2957. */
  2958. Vector3.prototype.scaleToRef = function (scale, result) {
  2959. result.x = this.x * scale;
  2960. result.y = this.y * scale;
  2961. result.z = this.z * scale;
  2962. return this;
  2963. };
  2964. /**
  2965. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2966. * @param scale defines the scale factor
  2967. * @param result defines the Vector3 object where to store the result
  2968. * @returns the unmodified current Vector3
  2969. */
  2970. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2971. result.x += this.x * scale;
  2972. result.y += this.y * scale;
  2973. result.z += this.z * scale;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2978. * @param otherVector defines the second operand
  2979. * @returns true if both vectors are equals
  2980. */
  2981. Vector3.prototype.equals = function (otherVector) {
  2982. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2983. };
  2984. /**
  2985. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2986. * @param otherVector defines the second operand
  2987. * @param epsilon defines the minimal distance to define values as equals
  2988. * @returns true if both vectors are distant less than epsilon
  2989. */
  2990. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2991. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2992. 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);
  2993. };
  2994. /**
  2995. * Returns true if the current Vector3 coordinates equals the given floats
  2996. * @param x defines the x coordinate of the operand
  2997. * @param y defines the y coordinate of the operand
  2998. * @param z defines the z coordinate of the operand
  2999. * @returns true if both vectors are equals
  3000. */
  3001. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3002. return this.x === x && this.y === y && this.z === z;
  3003. };
  3004. /**
  3005. * Multiplies the current Vector3 coordinates by the given ones
  3006. * @param otherVector defines the second operand
  3007. * @returns the current updated Vector3
  3008. */
  3009. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3010. this.x *= otherVector.x;
  3011. this.y *= otherVector.y;
  3012. this.z *= otherVector.z;
  3013. return this;
  3014. };
  3015. /**
  3016. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3017. * @param otherVector defines the second operand
  3018. * @returns the new Vector3
  3019. */
  3020. Vector3.prototype.multiply = function (otherVector) {
  3021. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3022. };
  3023. /**
  3024. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3025. * @param otherVector defines the second operand
  3026. * @param result defines the Vector3 object where to store the result
  3027. * @returns the current Vector3
  3028. */
  3029. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3030. result.x = this.x * otherVector.x;
  3031. result.y = this.y * otherVector.y;
  3032. result.z = this.z * otherVector.z;
  3033. return this;
  3034. };
  3035. /**
  3036. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3037. * @param x defines the x coordinate of the operand
  3038. * @param y defines the y coordinate of the operand
  3039. * @param z defines the z coordinate of the operand
  3040. * @returns the new Vector3
  3041. */
  3042. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3043. return new Vector3(this.x * x, this.y * y, this.z * z);
  3044. };
  3045. /**
  3046. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3047. * @param otherVector defines the second operand
  3048. * @returns the new Vector3
  3049. */
  3050. Vector3.prototype.divide = function (otherVector) {
  3051. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3052. };
  3053. /**
  3054. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3055. * @param otherVector defines the second operand
  3056. * @param result defines the Vector3 object where to store the result
  3057. * @returns the current Vector3
  3058. */
  3059. Vector3.prototype.divideToRef = function (otherVector, result) {
  3060. result.x = this.x / otherVector.x;
  3061. result.y = this.y / otherVector.y;
  3062. result.z = this.z / otherVector.z;
  3063. return this;
  3064. };
  3065. /**
  3066. * Divides the current Vector3 coordinates by the given ones.
  3067. * @param otherVector defines the second operand
  3068. * @returns the current updated Vector3
  3069. */
  3070. Vector3.prototype.divideInPlace = function (otherVector) {
  3071. return this.divideToRef(otherVector, this);
  3072. };
  3073. /**
  3074. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3075. * @param other defines the second operand
  3076. * @returns the current updated Vector3
  3077. */
  3078. Vector3.prototype.minimizeInPlace = function (other) {
  3079. if (other.x < this.x)
  3080. this.x = other.x;
  3081. if (other.y < this.y)
  3082. this.y = other.y;
  3083. if (other.z < this.z)
  3084. this.z = other.z;
  3085. return this;
  3086. };
  3087. /**
  3088. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3089. * @param other defines the second operand
  3090. * @returns the current updated Vector3
  3091. */
  3092. Vector3.prototype.maximizeInPlace = function (other) {
  3093. if (other.x > this.x)
  3094. this.x = other.x;
  3095. if (other.y > this.y)
  3096. this.y = other.y;
  3097. if (other.z > this.z)
  3098. this.z = other.z;
  3099. return this;
  3100. };
  3101. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3102. /**
  3103. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3104. */
  3105. get: function () {
  3106. var absX = Math.abs(this.x);
  3107. var absY = Math.abs(this.y);
  3108. if (absX !== absY) {
  3109. return true;
  3110. }
  3111. var absZ = Math.abs(this.z);
  3112. if (absX !== absZ) {
  3113. return true;
  3114. }
  3115. if (absY !== absZ) {
  3116. return true;
  3117. }
  3118. return false;
  3119. },
  3120. enumerable: true,
  3121. configurable: true
  3122. });
  3123. // Properties
  3124. /**
  3125. * Gets the length of the Vector3
  3126. * @returns the length of the Vecto3
  3127. */
  3128. Vector3.prototype.length = function () {
  3129. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3130. };
  3131. /**
  3132. * Gets the squared length of the Vector3
  3133. * @returns squared length of the Vector3
  3134. */
  3135. Vector3.prototype.lengthSquared = function () {
  3136. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3137. };
  3138. /**
  3139. * Normalize the current Vector3.
  3140. * Please note that this is an in place operation.
  3141. * @returns the current updated Vector3
  3142. */
  3143. Vector3.prototype.normalize = function () {
  3144. var len = this.length();
  3145. if (len === 0 || len === 1.0)
  3146. return this;
  3147. var num = 1.0 / len;
  3148. this.x *= num;
  3149. this.y *= num;
  3150. this.z *= num;
  3151. return this;
  3152. };
  3153. /**
  3154. * Normalize the current Vector3 to a new vector
  3155. * @returns the new Vector3
  3156. */
  3157. Vector3.prototype.normalizeToNew = function () {
  3158. var normalized = new Vector3(0, 0, 0);
  3159. this.normalizeToRef(normalized);
  3160. return normalized;
  3161. };
  3162. /**
  3163. * Normalize the current Vector3 to the reference
  3164. * @param reference define the Vector3 to update
  3165. * @returns the updated Vector3
  3166. */
  3167. Vector3.prototype.normalizeToRef = function (reference) {
  3168. var len = this.length();
  3169. if (len === 0 || len === 1.0) {
  3170. reference.set(this.x, this.y, this.z);
  3171. return reference;
  3172. }
  3173. var scale = 1.0 / len;
  3174. this.scaleToRef(scale, reference);
  3175. return reference;
  3176. };
  3177. /**
  3178. * Creates a new Vector3 copied from the current Vector3
  3179. * @returns the new Vector3
  3180. */
  3181. Vector3.prototype.clone = function () {
  3182. return new Vector3(this.x, this.y, this.z);
  3183. };
  3184. /**
  3185. * Copies the given vector coordinates to the current Vector3 ones
  3186. * @param source defines the source Vector3
  3187. * @returns the current updated Vector3
  3188. */
  3189. Vector3.prototype.copyFrom = function (source) {
  3190. this.x = source.x;
  3191. this.y = source.y;
  3192. this.z = source.z;
  3193. return this;
  3194. };
  3195. /**
  3196. * Copies the given floats to the current Vector3 coordinates
  3197. * @param x defines the x coordinate of the operand
  3198. * @param y defines the y coordinate of the operand
  3199. * @param z defines the z coordinate of the operand
  3200. * @returns the current updated Vector3
  3201. */
  3202. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3203. this.x = x;
  3204. this.y = y;
  3205. this.z = z;
  3206. return this;
  3207. };
  3208. /**
  3209. * Copies the given floats to the current Vector3 coordinates
  3210. * @param x defines the x coordinate of the operand
  3211. * @param y defines the y coordinate of the operand
  3212. * @param z defines the z coordinate of the operand
  3213. * @returns the current updated Vector3
  3214. */
  3215. Vector3.prototype.set = function (x, y, z) {
  3216. return this.copyFromFloats(x, y, z);
  3217. };
  3218. // Statics
  3219. /**
  3220. * Get the clip factor between two vectors
  3221. * @param vector0 defines the first operand
  3222. * @param vector1 defines the second operand
  3223. * @param axis defines the axis to use
  3224. * @param size defines the size along the axis
  3225. * @returns the clip factor
  3226. */
  3227. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3228. var d0 = Vector3.Dot(vector0, axis) - size;
  3229. var d1 = Vector3.Dot(vector1, axis) - size;
  3230. var s = d0 / (d0 - d1);
  3231. return s;
  3232. };
  3233. /**
  3234. * Get angle between two vectors
  3235. * @param vector0 angle between vector0 and vector1
  3236. * @param vector1 angle between vector0 and vector1
  3237. * @param normal direction of the normal
  3238. * @return the angle between vector0 and vector1
  3239. */
  3240. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3241. var v0 = vector0.clone().normalize();
  3242. var v1 = vector1.clone().normalize();
  3243. var dot = Vector3.Dot(v0, v1);
  3244. var n = Vector3.Cross(v0, v1);
  3245. if (Vector3.Dot(n, normal) > 0) {
  3246. return Math.acos(dot);
  3247. }
  3248. return -Math.acos(dot);
  3249. };
  3250. /**
  3251. * Returns a new Vector3 set from the index "offset" of the given array
  3252. * @param array defines the source array
  3253. * @param offset defines the offset in the source array
  3254. * @returns the new Vector3
  3255. */
  3256. Vector3.FromArray = function (array, offset) {
  3257. if (!offset) {
  3258. offset = 0;
  3259. }
  3260. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3264. * This function is deprecated. Use FromArray instead
  3265. * @param array defines the source array
  3266. * @param offset defines the offset in the source array
  3267. * @returns the new Vector3
  3268. */
  3269. Vector3.FromFloatArray = function (array, offset) {
  3270. return Vector3.FromArray(array, offset);
  3271. };
  3272. /**
  3273. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3274. * @param array defines the source array
  3275. * @param offset defines the offset in the source array
  3276. * @param result defines the Vector3 where to store the result
  3277. */
  3278. Vector3.FromArrayToRef = function (array, offset, result) {
  3279. result.x = array[offset];
  3280. result.y = array[offset + 1];
  3281. result.z = array[offset + 2];
  3282. };
  3283. /**
  3284. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3285. * This function is deprecated. Use FromArrayToRef instead.
  3286. * @param array defines the source array
  3287. * @param offset defines the offset in the source array
  3288. * @param result defines the Vector3 where to store the result
  3289. */
  3290. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3291. return Vector3.FromArrayToRef(array, offset, result);
  3292. };
  3293. /**
  3294. * Sets the given vector "result" with the given floats.
  3295. * @param x defines the x coordinate of the source
  3296. * @param y defines the y coordinate of the source
  3297. * @param z defines the z coordinate of the source
  3298. * @param result defines the Vector3 where to store the result
  3299. */
  3300. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3301. result.x = x;
  3302. result.y = y;
  3303. result.z = z;
  3304. };
  3305. /**
  3306. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3307. * @returns a new empty Vector3
  3308. */
  3309. Vector3.Zero = function () {
  3310. return new Vector3(0.0, 0.0, 0.0);
  3311. };
  3312. /**
  3313. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3314. * @returns a new unit Vector3
  3315. */
  3316. Vector3.One = function () {
  3317. return new Vector3(1.0, 1.0, 1.0);
  3318. };
  3319. /**
  3320. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3321. * @returns a new up Vector3
  3322. */
  3323. Vector3.Up = function () {
  3324. return new Vector3(0.0, 1.0, 0.0);
  3325. };
  3326. /**
  3327. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3328. * @returns a new forward Vector3
  3329. */
  3330. Vector3.Forward = function () {
  3331. return new Vector3(0.0, 0.0, 1.0);
  3332. };
  3333. /**
  3334. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3335. * @returns a new right Vector3
  3336. */
  3337. Vector3.Right = function () {
  3338. return new Vector3(1.0, 0.0, 0.0);
  3339. };
  3340. /**
  3341. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3342. * @returns a new left Vector3
  3343. */
  3344. Vector3.Left = function () {
  3345. return new Vector3(-1.0, 0.0, 0.0);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3349. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3350. * @param vector defines the Vector3 to transform
  3351. * @param transformation defines the transformation matrix
  3352. * @returns the transformed Vector3
  3353. */
  3354. Vector3.TransformCoordinates = function (vector, transformation) {
  3355. var result = Vector3.Zero();
  3356. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3357. return result;
  3358. };
  3359. /**
  3360. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3361. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3362. * @param vector defines the Vector3 to transform
  3363. * @param transformation defines the transformation matrix
  3364. * @param result defines the Vector3 where to store the result
  3365. */
  3366. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3367. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3368. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3369. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3370. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3371. result.x = x / w;
  3372. result.y = y / w;
  3373. result.z = z / w;
  3374. };
  3375. /**
  3376. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3377. * This method computes tranformed coordinates only, not transformed direction vectors
  3378. * @param x define the x coordinate of the source vector
  3379. * @param y define the y coordinate of the source vector
  3380. * @param z define the z coordinate of the source vector
  3381. * @param transformation defines the transformation matrix
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3385. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3386. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3387. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3388. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3389. result.x = rx / rw;
  3390. result.y = ry / rw;
  3391. result.z = rz / rw;
  3392. };
  3393. /**
  3394. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3395. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3396. * @param vector defines the Vector3 to transform
  3397. * @param transformation defines the transformation matrix
  3398. * @returns the new Vector3
  3399. */
  3400. Vector3.TransformNormal = function (vector, transformation) {
  3401. var result = Vector3.Zero();
  3402. Vector3.TransformNormalToRef(vector, transformation, result);
  3403. return result;
  3404. };
  3405. /**
  3406. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3407. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3408. * @param vector defines the Vector3 to transform
  3409. * @param transformation defines the transformation matrix
  3410. * @param result defines the Vector3 where to store the result
  3411. */
  3412. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3413. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3414. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3415. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3416. result.x = x;
  3417. result.y = y;
  3418. result.z = z;
  3419. };
  3420. /**
  3421. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3422. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3423. * @param x define the x coordinate of the source vector
  3424. * @param y define the y coordinate of the source vector
  3425. * @param z define the z coordinate of the source vector
  3426. * @param transformation defines the transformation matrix
  3427. * @param result defines the Vector3 where to store the result
  3428. */
  3429. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3430. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3431. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3432. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3436. * @param value1 defines the first control point
  3437. * @param value2 defines the second control point
  3438. * @param value3 defines the third control point
  3439. * @param value4 defines the fourth control point
  3440. * @param amount defines the amount on the spline to use
  3441. * @returns the new Vector3
  3442. */
  3443. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3444. var squared = amount * amount;
  3445. var cubed = amount * squared;
  3446. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3447. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3448. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3449. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3450. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3451. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3452. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3453. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3454. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3455. return new Vector3(x, y, z);
  3456. };
  3457. /**
  3458. * 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"
  3459. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3460. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3461. * @param value defines the current value
  3462. * @param min defines the lower range value
  3463. * @param max defines the upper range value
  3464. * @returns the new Vector3
  3465. */
  3466. Vector3.Clamp = function (value, min, max) {
  3467. var x = value.x;
  3468. x = (x > max.x) ? max.x : x;
  3469. x = (x < min.x) ? min.x : x;
  3470. var y = value.y;
  3471. y = (y > max.y) ? max.y : y;
  3472. y = (y < min.y) ? min.y : y;
  3473. var z = value.z;
  3474. z = (z > max.z) ? max.z : z;
  3475. z = (z < min.z) ? min.z : z;
  3476. return new Vector3(x, y, z);
  3477. };
  3478. /**
  3479. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3480. * @param value1 defines the first control point
  3481. * @param tangent1 defines the first tangent vector
  3482. * @param value2 defines the second control point
  3483. * @param tangent2 defines the second tangent vector
  3484. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3485. * @returns the new Vector3
  3486. */
  3487. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3488. var squared = amount * amount;
  3489. var cubed = amount * squared;
  3490. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3491. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3492. var part3 = (cubed - (2.0 * squared)) + amount;
  3493. var part4 = cubed - squared;
  3494. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3495. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3496. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3497. return new Vector3(x, y, z);
  3498. };
  3499. /**
  3500. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3501. * @param start defines the start value
  3502. * @param end defines the end value
  3503. * @param amount max defines amount between both (between 0 and 1)
  3504. * @returns the new Vector3
  3505. */
  3506. Vector3.Lerp = function (start, end, amount) {
  3507. var result = new Vector3(0, 0, 0);
  3508. Vector3.LerpToRef(start, end, amount, result);
  3509. return result;
  3510. };
  3511. /**
  3512. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3513. * @param start defines the start value
  3514. * @param end defines the end value
  3515. * @param amount max defines amount between both (between 0 and 1)
  3516. * @param result defines the Vector3 where to store the result
  3517. */
  3518. Vector3.LerpToRef = function (start, end, amount, result) {
  3519. result.x = start.x + ((end.x - start.x) * amount);
  3520. result.y = start.y + ((end.y - start.y) * amount);
  3521. result.z = start.z + ((end.z - start.z) * amount);
  3522. };
  3523. /**
  3524. * Returns the dot product (float) between the vectors "left" and "right"
  3525. * @param left defines the left operand
  3526. * @param right defines the right operand
  3527. * @returns the dot product
  3528. */
  3529. Vector3.Dot = function (left, right) {
  3530. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3531. };
  3532. /**
  3533. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3534. * The cross product is then orthogonal to both "left" and "right"
  3535. * @param left defines the left operand
  3536. * @param right defines the right operand
  3537. * @returns the cross product
  3538. */
  3539. Vector3.Cross = function (left, right) {
  3540. var result = Vector3.Zero();
  3541. Vector3.CrossToRef(left, right, result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the given vector "result" with the cross product of "left" and "right"
  3546. * The cross product is then orthogonal to both "left" and "right"
  3547. * @param left defines the left operand
  3548. * @param right defines the right operand
  3549. * @param result defines the Vector3 where to store the result
  3550. */
  3551. Vector3.CrossToRef = function (left, right, result) {
  3552. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3553. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3554. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3555. result.copyFrom(MathTmp.Vector3[0]);
  3556. };
  3557. /**
  3558. * Returns a new Vector3 as the normalization of the given vector
  3559. * @param vector defines the Vector3 to normalize
  3560. * @returns the new Vector3
  3561. */
  3562. Vector3.Normalize = function (vector) {
  3563. var result = Vector3.Zero();
  3564. Vector3.NormalizeToRef(vector, result);
  3565. return result;
  3566. };
  3567. /**
  3568. * Sets the given vector "result" with the normalization of the given first vector
  3569. * @param vector defines the Vector3 to normalize
  3570. * @param result defines the Vector3 where to store the result
  3571. */
  3572. Vector3.NormalizeToRef = function (vector, result) {
  3573. result.copyFrom(vector);
  3574. result.normalize();
  3575. };
  3576. /**
  3577. * Project a Vector3 onto screen space
  3578. * @param vector defines the Vector3 to project
  3579. * @param world defines the world matrix to use
  3580. * @param transform defines the transform (view x projection) matrix to use
  3581. * @param viewport defines the screen viewport to use
  3582. * @returns the new Vector3
  3583. */
  3584. Vector3.Project = function (vector, world, transform, viewport) {
  3585. var cw = viewport.width;
  3586. var ch = viewport.height;
  3587. var cx = viewport.x;
  3588. var cy = viewport.y;
  3589. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3590. 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);
  3591. var matrix = MathTmp.Matrix[0];
  3592. world.multiplyToRef(transform, matrix);
  3593. matrix.multiplyToRef(viewportMatrix, matrix);
  3594. return Vector3.TransformCoordinates(vector, matrix);
  3595. };
  3596. /**
  3597. * Unproject from screen space to object space
  3598. * @param source defines the screen space Vector3 to use
  3599. * @param viewportWidth defines the current width of the viewport
  3600. * @param viewportHeight defines the current height of the viewport
  3601. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3602. * @param transform defines the transform (view x projection) matrix to use
  3603. * @returns the new Vector3
  3604. */
  3605. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3606. var matrix = MathTmp.Matrix[0];
  3607. world.multiplyToRef(transform, matrix);
  3608. matrix.invert();
  3609. source.x = source.x / viewportWidth * 2 - 1;
  3610. source.y = -(source.y / viewportHeight * 2 - 1);
  3611. var vector = Vector3.TransformCoordinates(source, matrix);
  3612. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3613. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3614. vector = vector.scale(1.0 / num);
  3615. }
  3616. return vector;
  3617. };
  3618. /**
  3619. * Unproject from screen space to object space
  3620. * @param source defines the screen space Vector3 to use
  3621. * @param viewportWidth defines the current width of the viewport
  3622. * @param viewportHeight defines the current height of the viewport
  3623. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3624. * @param view defines the view matrix to use
  3625. * @param projection defines the projection matrix to use
  3626. * @returns the new Vector3
  3627. */
  3628. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3629. var result = Vector3.Zero();
  3630. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3631. return result;
  3632. };
  3633. /**
  3634. * Unproject from screen space to object space
  3635. * @param source defines the screen space Vector3 to use
  3636. * @param viewportWidth defines the current width of the viewport
  3637. * @param viewportHeight defines the current height of the viewport
  3638. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3639. * @param view defines the view matrix to use
  3640. * @param projection defines the projection matrix to use
  3641. * @param result defines the Vector3 where to store the result
  3642. */
  3643. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3644. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3645. };
  3646. /**
  3647. * Unproject from screen space to object space
  3648. * @param sourceX defines the screen space x coordinate to use
  3649. * @param sourceY defines the screen space y coordinate to use
  3650. * @param sourceZ defines the screen space z coordinate to use
  3651. * @param viewportWidth defines the current width of the viewport
  3652. * @param viewportHeight defines the current height of the viewport
  3653. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3654. * @param view defines the view matrix to use
  3655. * @param projection defines the projection matrix to use
  3656. * @param result defines the Vector3 where to store the result
  3657. */
  3658. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3659. var matrix = MathTmp.Matrix[0];
  3660. world.multiplyToRef(view, matrix);
  3661. matrix.multiplyToRef(projection, matrix);
  3662. matrix.invert();
  3663. var screenSource = MathTmp.Vector3[0];
  3664. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3665. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3666. screenSource.z = 2 * sourceZ - 1.0;
  3667. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3668. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3669. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3670. result.scaleInPlace(1.0 / num);
  3671. }
  3672. };
  3673. /**
  3674. * Gets the minimal coordinate values between two Vector3
  3675. * @param left defines the first operand
  3676. * @param right defines the second operand
  3677. * @returns the new Vector3
  3678. */
  3679. Vector3.Minimize = function (left, right) {
  3680. var min = left.clone();
  3681. min.minimizeInPlace(right);
  3682. return min;
  3683. };
  3684. /**
  3685. * Gets the maximal coordinate values between two Vector3
  3686. * @param left defines the first operand
  3687. * @param right defines the second operand
  3688. * @returns the new Vector3
  3689. */
  3690. Vector3.Maximize = function (left, right) {
  3691. var max = left.clone();
  3692. max.maximizeInPlace(right);
  3693. return max;
  3694. };
  3695. /**
  3696. * Returns the distance between the vectors "value1" and "value2"
  3697. * @param value1 defines the first operand
  3698. * @param value2 defines the second operand
  3699. * @returns the distance
  3700. */
  3701. Vector3.Distance = function (value1, value2) {
  3702. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3703. };
  3704. /**
  3705. * Returns the squared distance between the vectors "value1" and "value2"
  3706. * @param value1 defines the first operand
  3707. * @param value2 defines the second operand
  3708. * @returns the squared distance
  3709. */
  3710. Vector3.DistanceSquared = function (value1, value2) {
  3711. var x = value1.x - value2.x;
  3712. var y = value1.y - value2.y;
  3713. var z = value1.z - value2.z;
  3714. return (x * x) + (y * y) + (z * z);
  3715. };
  3716. /**
  3717. * Returns a new Vector3 located at the center between "value1" and "value2"
  3718. * @param value1 defines the first operand
  3719. * @param value2 defines the second operand
  3720. * @returns the new Vector3
  3721. */
  3722. Vector3.Center = function (value1, value2) {
  3723. var center = value1.add(value2);
  3724. center.scaleInPlace(0.5);
  3725. return center;
  3726. };
  3727. /**
  3728. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3729. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3730. * to something in order to rotate it from its local system to the given target system
  3731. * Note: axis1, axis2 and axis3 are normalized during this operation
  3732. * @param axis1 defines the first axis
  3733. * @param axis2 defines the second axis
  3734. * @param axis3 defines the third axis
  3735. * @returns a new Vector3
  3736. */
  3737. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3738. var rotation = Vector3.Zero();
  3739. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3740. return rotation;
  3741. };
  3742. /**
  3743. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3744. * @param axis1 defines the first axis
  3745. * @param axis2 defines the second axis
  3746. * @param axis3 defines the third axis
  3747. * @param ref defines the Vector3 where to store the result
  3748. */
  3749. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3750. var quat = MathTmp.Quaternion[0];
  3751. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3752. quat.toEulerAnglesToRef(ref);
  3753. };
  3754. return Vector3;
  3755. }());
  3756. BABYLON.Vector3 = Vector3;
  3757. //Vector4 class created for EulerAngle class conversion to Quaternion
  3758. var Vector4 = /** @class */ (function () {
  3759. /**
  3760. * Creates a Vector4 object from the given floats.
  3761. */
  3762. function Vector4(x, y, z, w) {
  3763. this.x = x;
  3764. this.y = y;
  3765. this.z = z;
  3766. this.w = w;
  3767. }
  3768. /**
  3769. * Returns the string with the Vector4 coordinates.
  3770. */
  3771. Vector4.prototype.toString = function () {
  3772. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3773. };
  3774. /**
  3775. * Returns the string "Vector4".
  3776. */
  3777. Vector4.prototype.getClassName = function () {
  3778. return "Vector4";
  3779. };
  3780. /**
  3781. * Returns the Vector4 hash code.
  3782. */
  3783. Vector4.prototype.getHashCode = function () {
  3784. var hash = this.x || 0;
  3785. hash = (hash * 397) ^ (this.y || 0);
  3786. hash = (hash * 397) ^ (this.z || 0);
  3787. hash = (hash * 397) ^ (this.w || 0);
  3788. return hash;
  3789. };
  3790. // Operators
  3791. /**
  3792. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3793. */
  3794. Vector4.prototype.asArray = function () {
  3795. var result = new Array();
  3796. this.toArray(result, 0);
  3797. return result;
  3798. };
  3799. /**
  3800. * Populates the given array from the given index with the Vector4 coordinates.
  3801. * Returns the Vector4.
  3802. */
  3803. Vector4.prototype.toArray = function (array, index) {
  3804. if (index === undefined) {
  3805. index = 0;
  3806. }
  3807. array[index] = this.x;
  3808. array[index + 1] = this.y;
  3809. array[index + 2] = this.z;
  3810. array[index + 3] = this.w;
  3811. return this;
  3812. };
  3813. /**
  3814. * Adds the given vector to the current Vector4.
  3815. * Returns the updated Vector4.
  3816. */
  3817. Vector4.prototype.addInPlace = function (otherVector) {
  3818. this.x += otherVector.x;
  3819. this.y += otherVector.y;
  3820. this.z += otherVector.z;
  3821. this.w += otherVector.w;
  3822. return this;
  3823. };
  3824. /**
  3825. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3826. */
  3827. Vector4.prototype.add = function (otherVector) {
  3828. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3829. };
  3830. /**
  3831. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3832. * Returns the current Vector4.
  3833. */
  3834. Vector4.prototype.addToRef = function (otherVector, result) {
  3835. result.x = this.x + otherVector.x;
  3836. result.y = this.y + otherVector.y;
  3837. result.z = this.z + otherVector.z;
  3838. result.w = this.w + otherVector.w;
  3839. return this;
  3840. };
  3841. /**
  3842. * Subtract in place the given vector from the current Vector4.
  3843. * Returns the updated Vector4.
  3844. */
  3845. Vector4.prototype.subtractInPlace = function (otherVector) {
  3846. this.x -= otherVector.x;
  3847. this.y -= otherVector.y;
  3848. this.z -= otherVector.z;
  3849. this.w -= otherVector.w;
  3850. return this;
  3851. };
  3852. /**
  3853. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3854. */
  3855. Vector4.prototype.subtract = function (otherVector) {
  3856. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3857. };
  3858. /**
  3859. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3860. * Returns the current Vector4.
  3861. */
  3862. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3863. result.x = this.x - otherVector.x;
  3864. result.y = this.y - otherVector.y;
  3865. result.z = this.z - otherVector.z;
  3866. result.w = this.w - otherVector.w;
  3867. return this;
  3868. };
  3869. /**
  3870. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3871. */
  3872. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3873. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3874. };
  3875. /**
  3876. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3877. * Returns the current Vector4.
  3878. */
  3879. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3880. result.x = this.x - x;
  3881. result.y = this.y - y;
  3882. result.z = this.z - z;
  3883. result.w = this.w - w;
  3884. return this;
  3885. };
  3886. /**
  3887. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3888. */
  3889. Vector4.prototype.negate = function () {
  3890. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3891. };
  3892. /**
  3893. * Multiplies the current Vector4 coordinates by scale (float).
  3894. * Returns the updated Vector4.
  3895. */
  3896. Vector4.prototype.scaleInPlace = function (scale) {
  3897. this.x *= scale;
  3898. this.y *= scale;
  3899. this.z *= scale;
  3900. this.w *= scale;
  3901. return this;
  3902. };
  3903. /**
  3904. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3905. */
  3906. Vector4.prototype.scale = function (scale) {
  3907. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3908. };
  3909. /**
  3910. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3911. * Returns the current Vector4.
  3912. */
  3913. Vector4.prototype.scaleToRef = function (scale, result) {
  3914. result.x = this.x * scale;
  3915. result.y = this.y * scale;
  3916. result.z = this.z * scale;
  3917. result.w = this.w * scale;
  3918. return this;
  3919. };
  3920. /**
  3921. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3922. * @param scale defines the scale factor
  3923. * @param result defines the Vector4 object where to store the result
  3924. * @returns the unmodified current Vector4
  3925. */
  3926. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3927. result.x += this.x * scale;
  3928. result.y += this.y * scale;
  3929. result.z += this.z * scale;
  3930. result.w += this.w * scale;
  3931. return this;
  3932. };
  3933. /**
  3934. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3935. */
  3936. Vector4.prototype.equals = function (otherVector) {
  3937. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3938. };
  3939. /**
  3940. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3941. */
  3942. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3943. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3944. return otherVector
  3945. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3946. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3947. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3948. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3949. };
  3950. /**
  3951. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3952. */
  3953. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3954. return this.x === x && this.y === y && this.z === z && this.w === w;
  3955. };
  3956. /**
  3957. * Multiplies in place the current Vector4 by the given one.
  3958. * Returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3961. this.x *= otherVector.x;
  3962. this.y *= otherVector.y;
  3963. this.z *= otherVector.z;
  3964. this.w *= otherVector.w;
  3965. return this;
  3966. };
  3967. /**
  3968. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3969. */
  3970. Vector4.prototype.multiply = function (otherVector) {
  3971. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3972. };
  3973. /**
  3974. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3975. * Returns the current Vector4.
  3976. */
  3977. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3978. result.x = this.x * otherVector.x;
  3979. result.y = this.y * otherVector.y;
  3980. result.z = this.z * otherVector.z;
  3981. result.w = this.w * otherVector.w;
  3982. return this;
  3983. };
  3984. /**
  3985. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3986. */
  3987. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3988. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3989. };
  3990. /**
  3991. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3992. */
  3993. Vector4.prototype.divide = function (otherVector) {
  3994. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3995. };
  3996. /**
  3997. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3998. * Returns the current Vector4.
  3999. */
  4000. Vector4.prototype.divideToRef = function (otherVector, result) {
  4001. result.x = this.x / otherVector.x;
  4002. result.y = this.y / otherVector.y;
  4003. result.z = this.z / otherVector.z;
  4004. result.w = this.w / otherVector.w;
  4005. return this;
  4006. };
  4007. /**
  4008. * Divides the current Vector3 coordinates by the given ones.
  4009. * @returns the updated Vector3.
  4010. */
  4011. Vector4.prototype.divideInPlace = function (otherVector) {
  4012. return this.divideToRef(otherVector, this);
  4013. };
  4014. /**
  4015. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4016. * @param other defines the second operand
  4017. * @returns the current updated Vector4
  4018. */
  4019. Vector4.prototype.minimizeInPlace = function (other) {
  4020. if (other.x < this.x)
  4021. this.x = other.x;
  4022. if (other.y < this.y)
  4023. this.y = other.y;
  4024. if (other.z < this.z)
  4025. this.z = other.z;
  4026. if (other.w < this.w)
  4027. this.w = other.w;
  4028. return this;
  4029. };
  4030. /**
  4031. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4032. * @param other defines the second operand
  4033. * @returns the current updated Vector4
  4034. */
  4035. Vector4.prototype.maximizeInPlace = function (other) {
  4036. if (other.x > this.x)
  4037. this.x = other.x;
  4038. if (other.y > this.y)
  4039. this.y = other.y;
  4040. if (other.z > this.z)
  4041. this.z = other.z;
  4042. if (other.w > this.w)
  4043. this.w = other.w;
  4044. return this;
  4045. };
  4046. // Properties
  4047. /**
  4048. * Returns the Vector4 length (float).
  4049. */
  4050. Vector4.prototype.length = function () {
  4051. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4052. };
  4053. /**
  4054. * Returns the Vector4 squared length (float).
  4055. */
  4056. Vector4.prototype.lengthSquared = function () {
  4057. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4058. };
  4059. // Methods
  4060. /**
  4061. * Normalizes in place the Vector4.
  4062. * Returns the updated Vector4.
  4063. */
  4064. Vector4.prototype.normalize = function () {
  4065. var len = this.length();
  4066. if (len === 0)
  4067. return this;
  4068. var num = 1.0 / len;
  4069. this.x *= num;
  4070. this.y *= num;
  4071. this.z *= num;
  4072. this.w *= num;
  4073. return this;
  4074. };
  4075. /**
  4076. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4077. */
  4078. Vector4.prototype.toVector3 = function () {
  4079. return new Vector3(this.x, this.y, this.z);
  4080. };
  4081. /**
  4082. * Returns a new Vector4 copied from the current one.
  4083. */
  4084. Vector4.prototype.clone = function () {
  4085. return new Vector4(this.x, this.y, this.z, this.w);
  4086. };
  4087. /**
  4088. * Updates the current Vector4 with the given one coordinates.
  4089. * Returns the updated Vector4.
  4090. */
  4091. Vector4.prototype.copyFrom = function (source) {
  4092. this.x = source.x;
  4093. this.y = source.y;
  4094. this.z = source.z;
  4095. this.w = source.w;
  4096. return this;
  4097. };
  4098. /**
  4099. * Updates the current Vector4 coordinates with the given floats.
  4100. * Returns the updated Vector4.
  4101. */
  4102. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4103. this.x = x;
  4104. this.y = y;
  4105. this.z = z;
  4106. this.w = w;
  4107. return this;
  4108. };
  4109. /**
  4110. * Updates the current Vector4 coordinates with the given floats.
  4111. * Returns the updated Vector4.
  4112. */
  4113. Vector4.prototype.set = function (x, y, z, w) {
  4114. return this.copyFromFloats(x, y, z, w);
  4115. };
  4116. // Statics
  4117. /**
  4118. * Returns a new Vector4 set from the starting index of the given array.
  4119. */
  4120. Vector4.FromArray = function (array, offset) {
  4121. if (!offset) {
  4122. offset = 0;
  4123. }
  4124. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4125. };
  4126. /**
  4127. * Updates the given vector "result" from the starting index of the given array.
  4128. */
  4129. Vector4.FromArrayToRef = function (array, offset, result) {
  4130. result.x = array[offset];
  4131. result.y = array[offset + 1];
  4132. result.z = array[offset + 2];
  4133. result.w = array[offset + 3];
  4134. };
  4135. /**
  4136. * Updates the given vector "result" from the starting index of the given Float32Array.
  4137. */
  4138. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4139. Vector4.FromArrayToRef(array, offset, result);
  4140. };
  4141. /**
  4142. * Updates the given vector "result" coordinates from the given floats.
  4143. */
  4144. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4145. result.x = x;
  4146. result.y = y;
  4147. result.z = z;
  4148. result.w = w;
  4149. };
  4150. /**
  4151. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4152. */
  4153. Vector4.Zero = function () {
  4154. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4155. };
  4156. /**
  4157. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4158. */
  4159. Vector4.One = function () {
  4160. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4161. };
  4162. /**
  4163. * Returns a new normalized Vector4 from the given one.
  4164. */
  4165. Vector4.Normalize = function (vector) {
  4166. var result = Vector4.Zero();
  4167. Vector4.NormalizeToRef(vector, result);
  4168. return result;
  4169. };
  4170. /**
  4171. * Updates the given vector "result" from the normalization of the given one.
  4172. */
  4173. Vector4.NormalizeToRef = function (vector, result) {
  4174. result.copyFrom(vector);
  4175. result.normalize();
  4176. };
  4177. Vector4.Minimize = function (left, right) {
  4178. var min = left.clone();
  4179. min.minimizeInPlace(right);
  4180. return min;
  4181. };
  4182. Vector4.Maximize = function (left, right) {
  4183. var max = left.clone();
  4184. max.maximizeInPlace(right);
  4185. return max;
  4186. };
  4187. /**
  4188. * Returns the distance (float) between the vectors "value1" and "value2".
  4189. */
  4190. Vector4.Distance = function (value1, value2) {
  4191. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4192. };
  4193. /**
  4194. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4195. */
  4196. Vector4.DistanceSquared = function (value1, value2) {
  4197. var x = value1.x - value2.x;
  4198. var y = value1.y - value2.y;
  4199. var z = value1.z - value2.z;
  4200. var w = value1.w - value2.w;
  4201. return (x * x) + (y * y) + (z * z) + (w * w);
  4202. };
  4203. /**
  4204. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4205. */
  4206. Vector4.Center = function (value1, value2) {
  4207. var center = value1.add(value2);
  4208. center.scaleInPlace(0.5);
  4209. return center;
  4210. };
  4211. /**
  4212. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4213. * This methods computes transformed normalized direction vectors only.
  4214. */
  4215. Vector4.TransformNormal = function (vector, transformation) {
  4216. var result = Vector4.Zero();
  4217. Vector4.TransformNormalToRef(vector, transformation, result);
  4218. return result;
  4219. };
  4220. /**
  4221. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4222. * This methods computes transformed normalized direction vectors only.
  4223. */
  4224. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4225. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4226. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4227. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4228. result.x = x;
  4229. result.y = y;
  4230. result.z = z;
  4231. result.w = vector.w;
  4232. };
  4233. /**
  4234. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4235. * This methods computes transformed normalized direction vectors only.
  4236. */
  4237. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4238. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4239. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4240. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4241. result.w = w;
  4242. };
  4243. return Vector4;
  4244. }());
  4245. BABYLON.Vector4 = Vector4;
  4246. var Size = /** @class */ (function () {
  4247. /**
  4248. * Creates a Size object from the given width and height (floats).
  4249. */
  4250. function Size(width, height) {
  4251. this.width = width;
  4252. this.height = height;
  4253. }
  4254. // Returns a string with the Size width and height.
  4255. Size.prototype.toString = function () {
  4256. return "{W: " + this.width + ", H: " + this.height + "}";
  4257. };
  4258. /**
  4259. * Returns the string "Size"
  4260. */
  4261. Size.prototype.getClassName = function () {
  4262. return "Size";
  4263. };
  4264. /**
  4265. * Returns the Size hash code.
  4266. */
  4267. Size.prototype.getHashCode = function () {
  4268. var hash = this.width || 0;
  4269. hash = (hash * 397) ^ (this.height || 0);
  4270. return hash;
  4271. };
  4272. /**
  4273. * Updates the current size from the given one.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFrom = function (src) {
  4277. this.width = src.width;
  4278. this.height = src.height;
  4279. };
  4280. /**
  4281. * Updates in place the current Size from the given floats.
  4282. * Returns the updated Size.
  4283. */
  4284. Size.prototype.copyFromFloats = function (width, height) {
  4285. this.width = width;
  4286. this.height = height;
  4287. return this;
  4288. };
  4289. /**
  4290. * Updates in place the current Size from the given floats.
  4291. * Returns the updated Size.
  4292. */
  4293. Size.prototype.set = function (width, height) {
  4294. return this.copyFromFloats(width, height);
  4295. };
  4296. /**
  4297. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4298. */
  4299. Size.prototype.multiplyByFloats = function (w, h) {
  4300. return new Size(this.width * w, this.height * h);
  4301. };
  4302. /**
  4303. * Returns a new Size copied from the given one.
  4304. */
  4305. Size.prototype.clone = function () {
  4306. return new Size(this.width, this.height);
  4307. };
  4308. /**
  4309. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4310. */
  4311. Size.prototype.equals = function (other) {
  4312. if (!other) {
  4313. return false;
  4314. }
  4315. return (this.width === other.width) && (this.height === other.height);
  4316. };
  4317. Object.defineProperty(Size.prototype, "surface", {
  4318. /**
  4319. * Returns the surface of the Size : width * height (float).
  4320. */
  4321. get: function () {
  4322. return this.width * this.height;
  4323. },
  4324. enumerable: true,
  4325. configurable: true
  4326. });
  4327. /**
  4328. * Returns a new Size set to (0.0, 0.0)
  4329. */
  4330. Size.Zero = function () {
  4331. return new Size(0.0, 0.0);
  4332. };
  4333. /**
  4334. * Returns a new Size set as the addition result of the current Size and the given one.
  4335. */
  4336. Size.prototype.add = function (otherSize) {
  4337. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4338. return r;
  4339. };
  4340. /**
  4341. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4342. */
  4343. Size.prototype.subtract = function (otherSize) {
  4344. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4345. return r;
  4346. };
  4347. /**
  4348. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4349. */
  4350. Size.Lerp = function (start, end, amount) {
  4351. var w = start.width + ((end.width - start.width) * amount);
  4352. var h = start.height + ((end.height - start.height) * amount);
  4353. return new Size(w, h);
  4354. };
  4355. return Size;
  4356. }());
  4357. BABYLON.Size = Size;
  4358. /**
  4359. * Class used to store quaternion data
  4360. * @see https://en.wikipedia.org/wiki/Quaternion
  4361. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4362. */
  4363. var Quaternion = /** @class */ (function () {
  4364. /**
  4365. * Creates a new Quaternion from the given floats
  4366. * @param x defines the first component (0 by default)
  4367. * @param y defines the second component (0 by default)
  4368. * @param z defines the third component (0 by default)
  4369. * @param w defines the fourth component (1.0 by default)
  4370. */
  4371. function Quaternion(
  4372. /** defines the first component (0 by default) */
  4373. x,
  4374. /** defines the second component (0 by default) */
  4375. y,
  4376. /** defines the third component (0 by default) */
  4377. z,
  4378. /** defines the fourth component (1.0 by default) */
  4379. w) {
  4380. if (x === void 0) { x = 0.0; }
  4381. if (y === void 0) { y = 0.0; }
  4382. if (z === void 0) { z = 0.0; }
  4383. if (w === void 0) { w = 1.0; }
  4384. this.x = x;
  4385. this.y = y;
  4386. this.z = z;
  4387. this.w = w;
  4388. }
  4389. /**
  4390. * Gets a string representation for the current quaternion
  4391. * @returns a string with the Quaternion coordinates
  4392. */
  4393. Quaternion.prototype.toString = function () {
  4394. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4395. };
  4396. /**
  4397. * Gets the class name of the quaternion
  4398. * @returns the string "Quaternion"
  4399. */
  4400. Quaternion.prototype.getClassName = function () {
  4401. return "Quaternion";
  4402. };
  4403. /**
  4404. * Gets a hash code for this quaternion
  4405. * @returns the quaternion hash code
  4406. */
  4407. Quaternion.prototype.getHashCode = function () {
  4408. var hash = this.x || 0;
  4409. hash = (hash * 397) ^ (this.y || 0);
  4410. hash = (hash * 397) ^ (this.z || 0);
  4411. hash = (hash * 397) ^ (this.w || 0);
  4412. return hash;
  4413. };
  4414. /**
  4415. * Copy the quaternion to an array
  4416. * @returns a new array populated with 4 elements from the quaternion coordinates
  4417. */
  4418. Quaternion.prototype.asArray = function () {
  4419. return [this.x, this.y, this.z, this.w];
  4420. };
  4421. /**
  4422. * Check if two quaternions are equals
  4423. * @param otherQuaternion defines the second operand
  4424. * @return true if the current quaternion and the given one coordinates are strictly equals
  4425. */
  4426. Quaternion.prototype.equals = function (otherQuaternion) {
  4427. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4428. };
  4429. /**
  4430. * Clone the current quaternion
  4431. * @returns a new quaternion copied from the current one
  4432. */
  4433. Quaternion.prototype.clone = function () {
  4434. return new Quaternion(this.x, this.y, this.z, this.w);
  4435. };
  4436. /**
  4437. * Copy a quaternion to the current one
  4438. * @param other defines the other quaternion
  4439. * @returns the updated current quaternion
  4440. */
  4441. Quaternion.prototype.copyFrom = function (other) {
  4442. this.x = other.x;
  4443. this.y = other.y;
  4444. this.z = other.z;
  4445. this.w = other.w;
  4446. return this;
  4447. };
  4448. /**
  4449. * Updates the current quaternion with the given float coordinates
  4450. * @param x defines the x coordinate
  4451. * @param y defines the y coordinate
  4452. * @param z defines the z coordinate
  4453. * @param w defines the w coordinate
  4454. * @returns the updated current quaternion
  4455. */
  4456. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4457. this.x = x;
  4458. this.y = y;
  4459. this.z = z;
  4460. this.w = w;
  4461. return this;
  4462. };
  4463. /**
  4464. * Updates the current quaternion from the given float coordinates
  4465. * @param x defines the x coordinate
  4466. * @param y defines the y coordinate
  4467. * @param z defines the z coordinate
  4468. * @param w defines the w coordinate
  4469. * @returns the updated current quaternion
  4470. */
  4471. Quaternion.prototype.set = function (x, y, z, w) {
  4472. return this.copyFromFloats(x, y, z, w);
  4473. };
  4474. /**
  4475. * Adds two quaternions
  4476. * @param other defines the second operand
  4477. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4478. */
  4479. Quaternion.prototype.add = function (other) {
  4480. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4481. };
  4482. /**
  4483. * Add a quaternion to the current one
  4484. * @param other defines the quaternion to add
  4485. * @returns the current quaternion
  4486. */
  4487. Quaternion.prototype.addInPlace = function (other) {
  4488. this.x += other.x;
  4489. this.y += other.y;
  4490. this.z += other.z;
  4491. this.w += other.w;
  4492. return this;
  4493. };
  4494. /**
  4495. * Subtract two quaternions
  4496. * @param other defines the second operand
  4497. * @returns a new quaternion as the subtraction result of the given one from the current one
  4498. */
  4499. Quaternion.prototype.subtract = function (other) {
  4500. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4501. };
  4502. /**
  4503. * Multiplies the current quaternion by a scale factor
  4504. * @param value defines the scale factor
  4505. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4506. */
  4507. Quaternion.prototype.scale = function (value) {
  4508. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4509. };
  4510. /**
  4511. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4512. * @param scale defines the scale factor
  4513. * @param result defines the Quaternion object where to store the result
  4514. * @returns the unmodified current quaternion
  4515. */
  4516. Quaternion.prototype.scaleToRef = function (scale, result) {
  4517. result.x = this.x * scale;
  4518. result.y = this.y * scale;
  4519. result.z = this.z * scale;
  4520. result.w = this.w * scale;
  4521. return this;
  4522. };
  4523. /**
  4524. * Multiplies in place the current quaternion by a scale factor
  4525. * @param value defines the scale factor
  4526. * @returns the current modified quaternion
  4527. */
  4528. Quaternion.prototype.scaleInPlace = function (value) {
  4529. this.x *= value;
  4530. this.y *= value;
  4531. this.z *= value;
  4532. this.w *= value;
  4533. return this;
  4534. };
  4535. /**
  4536. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4537. * @param scale defines the scale factor
  4538. * @param result defines the Quaternion object where to store the result
  4539. * @returns the unmodified current quaternion
  4540. */
  4541. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4542. result.x += this.x * scale;
  4543. result.y += this.y * scale;
  4544. result.z += this.z * scale;
  4545. result.w += this.w * scale;
  4546. return this;
  4547. };
  4548. /**
  4549. * Multiplies two quaternions
  4550. * @param q1 defines the second operand
  4551. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4552. */
  4553. Quaternion.prototype.multiply = function (q1) {
  4554. var result = new Quaternion(0, 0, 0, 1.0);
  4555. this.multiplyToRef(q1, result);
  4556. return result;
  4557. };
  4558. /**
  4559. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4560. * @param q1 defines the second operand
  4561. * @param result defines the target quaternion
  4562. * @returns the current quaternion
  4563. */
  4564. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4565. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4566. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4567. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4568. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4569. result.copyFromFloats(x, y, z, w);
  4570. return this;
  4571. };
  4572. /**
  4573. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4574. * @param q1 defines the second operand
  4575. * @returns the currentupdated quaternion
  4576. */
  4577. Quaternion.prototype.multiplyInPlace = function (q1) {
  4578. this.multiplyToRef(q1, this);
  4579. return this;
  4580. };
  4581. /**
  4582. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4583. * @param ref defines the target quaternion
  4584. * @returns the current quaternion
  4585. */
  4586. Quaternion.prototype.conjugateToRef = function (ref) {
  4587. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4588. return this;
  4589. };
  4590. /**
  4591. * Conjugates in place (1-q) the current quaternion
  4592. * @returns the current updated quaternion
  4593. */
  4594. Quaternion.prototype.conjugateInPlace = function () {
  4595. this.x *= -1;
  4596. this.y *= -1;
  4597. this.z *= -1;
  4598. return this;
  4599. };
  4600. /**
  4601. * Conjugates in place (1-q) the current quaternion
  4602. * @returns a new quaternion
  4603. */
  4604. Quaternion.prototype.conjugate = function () {
  4605. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4606. return result;
  4607. };
  4608. /**
  4609. * Gets length of current quaternion
  4610. * @returns the quaternion length (float)
  4611. */
  4612. Quaternion.prototype.length = function () {
  4613. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4614. };
  4615. /**
  4616. * Normalize in place the current quaternion
  4617. * @returns the current updated quaternion
  4618. */
  4619. Quaternion.prototype.normalize = function () {
  4620. var length = 1.0 / this.length();
  4621. this.x *= length;
  4622. this.y *= length;
  4623. this.z *= length;
  4624. this.w *= length;
  4625. return this;
  4626. };
  4627. /**
  4628. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4629. * @param order is a reserved parameter and is ignore for now
  4630. * @returns a new Vector3 containing the Euler angles
  4631. */
  4632. Quaternion.prototype.toEulerAngles = function (order) {
  4633. if (order === void 0) { order = "YZX"; }
  4634. var result = Vector3.Zero();
  4635. this.toEulerAnglesToRef(result, order);
  4636. return result;
  4637. };
  4638. /**
  4639. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4640. * @param result defines the vector which will be filled with the Euler angles
  4641. * @param order is a reserved parameter and is ignore for now
  4642. * @returns the current unchanged quaternion
  4643. */
  4644. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4645. if (order === void 0) { order = "YZX"; }
  4646. var qz = this.z;
  4647. var qx = this.x;
  4648. var qy = this.y;
  4649. var qw = this.w;
  4650. var sqw = qw * qw;
  4651. var sqz = qz * qz;
  4652. var sqx = qx * qx;
  4653. var sqy = qy * qy;
  4654. var zAxisY = qy * qz - qx * qw;
  4655. var limit = .4999999;
  4656. if (zAxisY < -limit) {
  4657. result.y = 2 * Math.atan2(qy, qw);
  4658. result.x = Math.PI / 2;
  4659. result.z = 0;
  4660. }
  4661. else if (zAxisY > limit) {
  4662. result.y = 2 * Math.atan2(qy, qw);
  4663. result.x = -Math.PI / 2;
  4664. result.z = 0;
  4665. }
  4666. else {
  4667. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4668. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4669. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4670. }
  4671. return this;
  4672. };
  4673. /**
  4674. * Updates the given rotation matrix with the current quaternion values
  4675. * @param result defines the target matrix
  4676. * @returns the current unchanged quaternion
  4677. */
  4678. Quaternion.prototype.toRotationMatrix = function (result) {
  4679. var xx = this.x * this.x;
  4680. var yy = this.y * this.y;
  4681. var zz = this.z * this.z;
  4682. var xy = this.x * this.y;
  4683. var zw = this.z * this.w;
  4684. var zx = this.z * this.x;
  4685. var yw = this.y * this.w;
  4686. var yz = this.y * this.z;
  4687. var xw = this.x * this.w;
  4688. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4689. result.m[1] = 2.0 * (xy + zw);
  4690. result.m[2] = 2.0 * (zx - yw);
  4691. result.m[3] = 0;
  4692. result.m[4] = 2.0 * (xy - zw);
  4693. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4694. result.m[6] = 2.0 * (yz + xw);
  4695. result.m[7] = 0;
  4696. result.m[8] = 2.0 * (zx + yw);
  4697. result.m[9] = 2.0 * (yz - xw);
  4698. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4699. result.m[11] = 0;
  4700. result.m[12] = 0;
  4701. result.m[13] = 0;
  4702. result.m[14] = 0;
  4703. result.m[15] = 1.0;
  4704. result._markAsUpdated();
  4705. return this;
  4706. };
  4707. /**
  4708. * Updates the current quaternion from the given rotation matrix values
  4709. * @param matrix defines the source matrix
  4710. * @returns the current updated quaternion
  4711. */
  4712. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4713. Quaternion.FromRotationMatrixToRef(matrix, this);
  4714. return this;
  4715. };
  4716. // Statics
  4717. /**
  4718. * Creates a new quaternion from a rotation matrix
  4719. * @param matrix defines the source matrix
  4720. * @returns a new quaternion created from the given rotation matrix values
  4721. */
  4722. Quaternion.FromRotationMatrix = function (matrix) {
  4723. var result = new Quaternion();
  4724. Quaternion.FromRotationMatrixToRef(matrix, result);
  4725. return result;
  4726. };
  4727. /**
  4728. * Updates the given quaternion with the given rotation matrix values
  4729. * @param matrix defines the source matrix
  4730. * @param result defines the target quaternion
  4731. */
  4732. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4733. var data = matrix.m;
  4734. var m11 = data[0], m12 = data[4], m13 = data[8];
  4735. var m21 = data[1], m22 = data[5], m23 = data[9];
  4736. var m31 = data[2], m32 = data[6], m33 = data[10];
  4737. var trace = m11 + m22 + m33;
  4738. var s;
  4739. if (trace > 0) {
  4740. s = 0.5 / Math.sqrt(trace + 1.0);
  4741. result.w = 0.25 / s;
  4742. result.x = (m32 - m23) * s;
  4743. result.y = (m13 - m31) * s;
  4744. result.z = (m21 - m12) * s;
  4745. }
  4746. else if (m11 > m22 && m11 > m33) {
  4747. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4748. result.w = (m32 - m23) / s;
  4749. result.x = 0.25 * s;
  4750. result.y = (m12 + m21) / s;
  4751. result.z = (m13 + m31) / s;
  4752. }
  4753. else if (m22 > m33) {
  4754. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4755. result.w = (m13 - m31) / s;
  4756. result.x = (m12 + m21) / s;
  4757. result.y = 0.25 * s;
  4758. result.z = (m23 + m32) / s;
  4759. }
  4760. else {
  4761. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4762. result.w = (m21 - m12) / s;
  4763. result.x = (m13 + m31) / s;
  4764. result.y = (m23 + m32) / s;
  4765. result.z = 0.25 * s;
  4766. }
  4767. };
  4768. /**
  4769. * Creates an empty quaternion
  4770. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4771. */
  4772. Quaternion.Zero = function () {
  4773. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4774. };
  4775. /**
  4776. * Inverse a given quaternion
  4777. * @param q defines the source quaternion
  4778. * @returns a new quaternion as the inverted current quaternion
  4779. */
  4780. Quaternion.Inverse = function (q) {
  4781. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4782. };
  4783. /**
  4784. * Creates an identity quaternion
  4785. * @returns the identity quaternion
  4786. */
  4787. Quaternion.Identity = function () {
  4788. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4789. };
  4790. /**
  4791. * Gets a boolean indicating if the given quaternion is identity
  4792. * @param quaternion defines the quaternion to check
  4793. * @returns true if the quaternion is identity
  4794. */
  4795. Quaternion.IsIdentity = function (quaternion) {
  4796. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4797. };
  4798. /**
  4799. * Creates a quaternion from a rotation around an axis
  4800. * @param axis defines the axis to use
  4801. * @param angle defines the angle to use
  4802. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4803. */
  4804. Quaternion.RotationAxis = function (axis, angle) {
  4805. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4806. };
  4807. /**
  4808. * Creates a rotation around an axis and stores it into the given quaternion
  4809. * @param axis defines the axis to use
  4810. * @param angle defines the angle to use
  4811. * @param result defines the target quaternion
  4812. * @returns the target quaternion
  4813. */
  4814. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4815. var sin = Math.sin(angle / 2);
  4816. axis.normalize();
  4817. result.w = Math.cos(angle / 2);
  4818. result.x = axis.x * sin;
  4819. result.y = axis.y * sin;
  4820. result.z = axis.z * sin;
  4821. return result;
  4822. };
  4823. /**
  4824. * Creates a new quaternion from data stored into an array
  4825. * @param array defines the data source
  4826. * @param offset defines the offset in the source array where the data starts
  4827. * @returns a new quaternion
  4828. */
  4829. Quaternion.FromArray = function (array, offset) {
  4830. if (!offset) {
  4831. offset = 0;
  4832. }
  4833. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4834. };
  4835. /**
  4836. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4837. * @param yaw defines the rotation around Y axis
  4838. * @param pitch defines the rotation around X axis
  4839. * @param roll defines the rotation around Z axis
  4840. * @returns the new quaternion
  4841. */
  4842. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4843. var q = new Quaternion();
  4844. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4845. return q;
  4846. };
  4847. /**
  4848. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4849. * @param yaw defines the rotation around Y axis
  4850. * @param pitch defines the rotation around X axis
  4851. * @param roll defines the rotation around Z axis
  4852. * @param result defines the target quaternion
  4853. */
  4854. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4855. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4856. var halfRoll = roll * 0.5;
  4857. var halfPitch = pitch * 0.5;
  4858. var halfYaw = yaw * 0.5;
  4859. var sinRoll = Math.sin(halfRoll);
  4860. var cosRoll = Math.cos(halfRoll);
  4861. var sinPitch = Math.sin(halfPitch);
  4862. var cosPitch = Math.cos(halfPitch);
  4863. var sinYaw = Math.sin(halfYaw);
  4864. var cosYaw = Math.cos(halfYaw);
  4865. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4866. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4867. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4868. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4869. };
  4870. /**
  4871. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4872. * @param alpha defines the rotation around first axis
  4873. * @param beta defines the rotation around second axis
  4874. * @param gamma defines the rotation around third axis
  4875. * @returns the new quaternion
  4876. */
  4877. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4878. var result = new Quaternion();
  4879. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4880. return result;
  4881. };
  4882. /**
  4883. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4884. * @param alpha defines the rotation around first axis
  4885. * @param beta defines the rotation around second axis
  4886. * @param gamma defines the rotation around third axis
  4887. * @param result defines the target quaternion
  4888. */
  4889. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4890. // Produces a quaternion from Euler angles in the z-x-z orientation
  4891. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4892. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4893. var halfBeta = beta * 0.5;
  4894. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4895. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4896. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4897. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4898. };
  4899. /**
  4900. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4901. * @param axis1 defines the first axis
  4902. * @param axis2 defines the second axis
  4903. * @param axis3 defines the third axis
  4904. * @returns the new quaternion
  4905. */
  4906. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4907. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4908. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4909. return quat;
  4910. };
  4911. /**
  4912. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4913. * @param axis1 defines the first axis
  4914. * @param axis2 defines the second axis
  4915. * @param axis3 defines the third axis
  4916. * @param ref defines the target quaternion
  4917. */
  4918. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4919. var rotMat = MathTmp.Matrix[0];
  4920. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4921. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4922. };
  4923. /**
  4924. * Interpolates between two quaternions
  4925. * @param left defines first quaternion
  4926. * @param right defines second quaternion
  4927. * @param amount defines the gradient to use
  4928. * @returns the new interpolated quaternion
  4929. */
  4930. Quaternion.Slerp = function (left, right, amount) {
  4931. var result = Quaternion.Identity();
  4932. Quaternion.SlerpToRef(left, right, amount, result);
  4933. return result;
  4934. };
  4935. /**
  4936. * Interpolates between two quaternions and stores it into a target quaternion
  4937. * @param left defines first quaternion
  4938. * @param right defines second quaternion
  4939. * @param amount defines the gradient to use
  4940. * @param result defines the target quaternion
  4941. */
  4942. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4943. var num2;
  4944. var num3;
  4945. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4946. var flag = false;
  4947. if (num4 < 0) {
  4948. flag = true;
  4949. num4 = -num4;
  4950. }
  4951. if (num4 > 0.999999) {
  4952. num3 = 1 - amount;
  4953. num2 = flag ? -amount : amount;
  4954. }
  4955. else {
  4956. var num5 = Math.acos(num4);
  4957. var num6 = (1.0 / Math.sin(num5));
  4958. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4959. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4960. }
  4961. result.x = (num3 * left.x) + (num2 * right.x);
  4962. result.y = (num3 * left.y) + (num2 * right.y);
  4963. result.z = (num3 * left.z) + (num2 * right.z);
  4964. result.w = (num3 * left.w) + (num2 * right.w);
  4965. };
  4966. /**
  4967. * Interpolate between two quaternions using Hermite interpolation
  4968. * @param value1 defines first quaternion
  4969. * @param tangent1 defines the incoming tangent
  4970. * @param value2 defines second quaternion
  4971. * @param tangent2 defines the outgoing tangent
  4972. * @param amount defines the target quaternion
  4973. * @returns the new interpolated quaternion
  4974. */
  4975. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4976. var squared = amount * amount;
  4977. var cubed = amount * squared;
  4978. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4979. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4980. var part3 = (cubed - (2.0 * squared)) + amount;
  4981. var part4 = cubed - squared;
  4982. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4983. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4984. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4985. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4986. return new Quaternion(x, y, z, w);
  4987. };
  4988. return Quaternion;
  4989. }());
  4990. BABYLON.Quaternion = Quaternion;
  4991. /**
  4992. * Class used to store matrix data (4x4)
  4993. */
  4994. var Matrix = /** @class */ (function () {
  4995. /**
  4996. * Creates an empty matrix (filled with zeros)
  4997. */
  4998. function Matrix() {
  4999. this._isIdentity = false;
  5000. this._isIdentityDirty = true;
  5001. /**
  5002. * Gets or sets the internal data of the matrix
  5003. */
  5004. this.m = new Float32Array(16);
  5005. this._markAsUpdated();
  5006. }
  5007. /** @hidden */
  5008. Matrix.prototype._markAsUpdated = function () {
  5009. this.updateFlag = Matrix._updateFlagSeed++;
  5010. this._isIdentityDirty = true;
  5011. };
  5012. // Properties
  5013. /**
  5014. * Check if the current matrix is indentity
  5015. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5016. * @returns true is the matrix is the identity matrix
  5017. */
  5018. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5019. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5020. if (this._isIdentityDirty) {
  5021. this._isIdentityDirty = false;
  5022. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5023. this._isIdentity = false;
  5024. }
  5025. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5026. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5027. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5028. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5029. this._isIdentity = false;
  5030. }
  5031. else {
  5032. this._isIdentity = true;
  5033. }
  5034. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5035. this._isIdentity = false;
  5036. }
  5037. }
  5038. return this._isIdentity;
  5039. };
  5040. /**
  5041. * Gets the determinant of the matrix
  5042. * @returns the matrix determinant
  5043. */
  5044. Matrix.prototype.determinant = function () {
  5045. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5046. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5047. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5048. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5049. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5050. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5051. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5052. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5053. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5054. };
  5055. // Methods
  5056. /**
  5057. * Returns the matrix as a Float32Array
  5058. * @returns the matrix underlying array
  5059. */
  5060. Matrix.prototype.toArray = function () {
  5061. return this.m;
  5062. };
  5063. /**
  5064. * Returns the matrix as a Float32Array
  5065. * @returns the matrix underlying array.
  5066. */
  5067. Matrix.prototype.asArray = function () {
  5068. return this.toArray();
  5069. };
  5070. /**
  5071. * Inverts the current matrix in place
  5072. * @returns the current inverted matrix
  5073. */
  5074. Matrix.prototype.invert = function () {
  5075. this.invertToRef(this);
  5076. return this;
  5077. };
  5078. /**
  5079. * Sets all the matrix elements to zero
  5080. * @returns the current matrix
  5081. */
  5082. Matrix.prototype.reset = function () {
  5083. for (var index = 0; index < 16; index++) {
  5084. this.m[index] = 0.0;
  5085. }
  5086. this._markAsUpdated();
  5087. return this;
  5088. };
  5089. /**
  5090. * Adds the current matrix with a second one
  5091. * @param other defines the matrix to add
  5092. * @returns a new matrix as the addition of the current matrix and the given one
  5093. */
  5094. Matrix.prototype.add = function (other) {
  5095. var result = new Matrix();
  5096. this.addToRef(other, result);
  5097. return result;
  5098. };
  5099. /**
  5100. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5101. * @param other defines the matrix to add
  5102. * @param result defines the target matrix
  5103. * @returns the current matrix
  5104. */
  5105. Matrix.prototype.addToRef = function (other, result) {
  5106. for (var index = 0; index < 16; index++) {
  5107. result.m[index] = this.m[index] + other.m[index];
  5108. }
  5109. result._markAsUpdated();
  5110. return this;
  5111. };
  5112. /**
  5113. * Adds in place the given matrix to the current matrix
  5114. * @param other defines the second operand
  5115. * @returns the current updated matrix
  5116. */
  5117. Matrix.prototype.addToSelf = function (other) {
  5118. for (var index = 0; index < 16; index++) {
  5119. this.m[index] += other.m[index];
  5120. }
  5121. this._markAsUpdated();
  5122. return this;
  5123. };
  5124. /**
  5125. * Sets the given matrix to the current inverted Matrix
  5126. * @param other defines the target matrix
  5127. * @returns the unmodified current matrix
  5128. */
  5129. Matrix.prototype.invertToRef = function (other) {
  5130. var l1 = this.m[0];
  5131. var l2 = this.m[1];
  5132. var l3 = this.m[2];
  5133. var l4 = this.m[3];
  5134. var l5 = this.m[4];
  5135. var l6 = this.m[5];
  5136. var l7 = this.m[6];
  5137. var l8 = this.m[7];
  5138. var l9 = this.m[8];
  5139. var l10 = this.m[9];
  5140. var l11 = this.m[10];
  5141. var l12 = this.m[11];
  5142. var l13 = this.m[12];
  5143. var l14 = this.m[13];
  5144. var l15 = this.m[14];
  5145. var l16 = this.m[15];
  5146. var l17 = (l11 * l16) - (l12 * l15);
  5147. var l18 = (l10 * l16) - (l12 * l14);
  5148. var l19 = (l10 * l15) - (l11 * l14);
  5149. var l20 = (l9 * l16) - (l12 * l13);
  5150. var l21 = (l9 * l15) - (l11 * l13);
  5151. var l22 = (l9 * l14) - (l10 * l13);
  5152. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5153. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5154. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5155. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5156. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5157. var l28 = (l7 * l16) - (l8 * l15);
  5158. var l29 = (l6 * l16) - (l8 * l14);
  5159. var l30 = (l6 * l15) - (l7 * l14);
  5160. var l31 = (l5 * l16) - (l8 * l13);
  5161. var l32 = (l5 * l15) - (l7 * l13);
  5162. var l33 = (l5 * l14) - (l6 * l13);
  5163. var l34 = (l7 * l12) - (l8 * l11);
  5164. var l35 = (l6 * l12) - (l8 * l10);
  5165. var l36 = (l6 * l11) - (l7 * l10);
  5166. var l37 = (l5 * l12) - (l8 * l9);
  5167. var l38 = (l5 * l11) - (l7 * l9);
  5168. var l39 = (l5 * l10) - (l6 * l9);
  5169. other.m[0] = l23 * l27;
  5170. other.m[4] = l24 * l27;
  5171. other.m[8] = l25 * l27;
  5172. other.m[12] = l26 * l27;
  5173. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5174. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5175. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5176. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5177. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5178. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5179. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5180. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5181. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5182. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5183. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5184. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5185. other._markAsUpdated();
  5186. return this;
  5187. };
  5188. /**
  5189. * Inserts the translation vector (using 3 floats) in the current matrix
  5190. * @param x defines the 1st component of the translation
  5191. * @param y defines the 2nd component of the translation
  5192. * @param z defines the 3rd component of the translation
  5193. * @returns the current updated matrix
  5194. */
  5195. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5196. this.m[12] = x;
  5197. this.m[13] = y;
  5198. this.m[14] = z;
  5199. this._markAsUpdated();
  5200. return this;
  5201. };
  5202. /**
  5203. * Inserts the translation vector in the current matrix
  5204. * @param vector3 defines the translation to insert
  5205. * @returns the current updated matrix
  5206. */
  5207. Matrix.prototype.setTranslation = function (vector3) {
  5208. this.m[12] = vector3.x;
  5209. this.m[13] = vector3.y;
  5210. this.m[14] = vector3.z;
  5211. this._markAsUpdated();
  5212. return this;
  5213. };
  5214. /**
  5215. * Gets the translation value of the current matrix
  5216. * @returns a new Vector3 as the extracted translation from the matrix
  5217. */
  5218. Matrix.prototype.getTranslation = function () {
  5219. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5220. };
  5221. /**
  5222. * Fill a Vector3 with the extracted translation from the matrix
  5223. * @param result defines the Vector3 where to store the translation
  5224. * @returns the current matrix
  5225. */
  5226. Matrix.prototype.getTranslationToRef = function (result) {
  5227. result.x = this.m[12];
  5228. result.y = this.m[13];
  5229. result.z = this.m[14];
  5230. return this;
  5231. };
  5232. /**
  5233. * Remove rotation and scaling part from the matrix
  5234. * @returns the updated matrix
  5235. */
  5236. Matrix.prototype.removeRotationAndScaling = function () {
  5237. this.setRowFromFloats(0, 1, 0, 0, 0);
  5238. this.setRowFromFloats(1, 0, 1, 0, 0);
  5239. this.setRowFromFloats(2, 0, 0, 1, 0);
  5240. return this;
  5241. };
  5242. /**
  5243. * Multiply two matrices
  5244. * @param other defines the second operand
  5245. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5246. */
  5247. Matrix.prototype.multiply = function (other) {
  5248. var result = new Matrix();
  5249. this.multiplyToRef(other, result);
  5250. return result;
  5251. };
  5252. /**
  5253. * Copy the current matrix from the given one
  5254. * @param other defines the source matrix
  5255. * @returns the current updated matrix
  5256. */
  5257. Matrix.prototype.copyFrom = function (other) {
  5258. for (var index = 0; index < 16; index++) {
  5259. this.m[index] = other.m[index];
  5260. }
  5261. this._markAsUpdated();
  5262. return this;
  5263. };
  5264. /**
  5265. * Populates the given array from the starting index with the current matrix values
  5266. * @param array defines the target array
  5267. * @param offset defines the offset in the target array where to start storing values
  5268. * @returns the current matrix
  5269. */
  5270. Matrix.prototype.copyToArray = function (array, offset) {
  5271. if (offset === void 0) { offset = 0; }
  5272. for (var index = 0; index < 16; index++) {
  5273. array[offset + index] = this.m[index];
  5274. }
  5275. return this;
  5276. };
  5277. /**
  5278. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5279. * @param other defines the second operand
  5280. * @param result defines the matrix where to store the multiplication
  5281. * @returns the current matrix
  5282. */
  5283. Matrix.prototype.multiplyToRef = function (other, result) {
  5284. this.multiplyToArray(other, result.m, 0);
  5285. result._markAsUpdated();
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the array where to store the multiplication
  5292. * @param offset defines the offset in the target array where to start storing values
  5293. * @returns the current matrix
  5294. */
  5295. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5296. var tm0 = this.m[0];
  5297. var tm1 = this.m[1];
  5298. var tm2 = this.m[2];
  5299. var tm3 = this.m[3];
  5300. var tm4 = this.m[4];
  5301. var tm5 = this.m[5];
  5302. var tm6 = this.m[6];
  5303. var tm7 = this.m[7];
  5304. var tm8 = this.m[8];
  5305. var tm9 = this.m[9];
  5306. var tm10 = this.m[10];
  5307. var tm11 = this.m[11];
  5308. var tm12 = this.m[12];
  5309. var tm13 = this.m[13];
  5310. var tm14 = this.m[14];
  5311. var tm15 = this.m[15];
  5312. var om0 = other.m[0];
  5313. var om1 = other.m[1];
  5314. var om2 = other.m[2];
  5315. var om3 = other.m[3];
  5316. var om4 = other.m[4];
  5317. var om5 = other.m[5];
  5318. var om6 = other.m[6];
  5319. var om7 = other.m[7];
  5320. var om8 = other.m[8];
  5321. var om9 = other.m[9];
  5322. var om10 = other.m[10];
  5323. var om11 = other.m[11];
  5324. var om12 = other.m[12];
  5325. var om13 = other.m[13];
  5326. var om14 = other.m[14];
  5327. var om15 = other.m[15];
  5328. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5329. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5330. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5331. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5332. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5333. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5334. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5335. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5336. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5337. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5338. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5339. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5340. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5341. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5342. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5343. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5344. return this;
  5345. };
  5346. /**
  5347. * Check equality between this matrix and a second one
  5348. * @param value defines the second matrix to compare
  5349. * @returns true is the current matrix and the given one values are strictly equal
  5350. */
  5351. Matrix.prototype.equals = function (value) {
  5352. return value &&
  5353. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5354. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5355. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5356. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5357. };
  5358. /**
  5359. * Clone the current matrix
  5360. * @returns a new matrix from the current matrix
  5361. */
  5362. Matrix.prototype.clone = function () {
  5363. 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]);
  5364. };
  5365. /**
  5366. * Returns the name of the current matrix class
  5367. * @returns the string "Matrix"
  5368. */
  5369. Matrix.prototype.getClassName = function () {
  5370. return "Matrix";
  5371. };
  5372. /**
  5373. * Gets the hash code of the current matrix
  5374. * @returns the hash code
  5375. */
  5376. Matrix.prototype.getHashCode = function () {
  5377. var hash = this.m[0] || 0;
  5378. for (var i = 1; i < 16; i++) {
  5379. hash = (hash * 397) ^ (this.m[i] || 0);
  5380. }
  5381. return hash;
  5382. };
  5383. /**
  5384. * Decomposes the current Matrix into a translation, rotation and scaling components
  5385. * @param scale defines the scale vector3 given as a reference to update
  5386. * @param rotation defines the rotation quaternion given as a reference to update
  5387. * @param translation defines the translation vector3 given as a reference to update
  5388. * @returns true if operation was successful
  5389. */
  5390. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5391. if (translation) {
  5392. translation.x = this.m[12];
  5393. translation.y = this.m[13];
  5394. translation.z = this.m[14];
  5395. }
  5396. scale = scale || MathTmp.Vector3[0];
  5397. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5398. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5399. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5400. if (this.determinant() <= 0) {
  5401. scale.y *= -1;
  5402. }
  5403. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5404. if (rotation) {
  5405. rotation.x = 0;
  5406. rotation.y = 0;
  5407. rotation.z = 0;
  5408. rotation.w = 1;
  5409. }
  5410. return false;
  5411. }
  5412. if (rotation) {
  5413. 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]);
  5414. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5415. }
  5416. return true;
  5417. };
  5418. /**
  5419. * Gets specific row of the matrix
  5420. * @param index defines the number of the row to get
  5421. * @returns the index-th row of the current matrix as a new Vector4
  5422. */
  5423. Matrix.prototype.getRow = function (index) {
  5424. if (index < 0 || index > 3) {
  5425. return null;
  5426. }
  5427. var i = index * 4;
  5428. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5429. };
  5430. /**
  5431. * Sets the index-th row of the current matrix to the vector4 values
  5432. * @param index defines the number of the row to set
  5433. * @param row defines the target vector4
  5434. * @returns the updated current matrix
  5435. */
  5436. Matrix.prototype.setRow = function (index, row) {
  5437. if (index < 0 || index > 3) {
  5438. return this;
  5439. }
  5440. var i = index * 4;
  5441. this.m[i + 0] = row.x;
  5442. this.m[i + 1] = row.y;
  5443. this.m[i + 2] = row.z;
  5444. this.m[i + 3] = row.w;
  5445. this._markAsUpdated();
  5446. return this;
  5447. };
  5448. /**
  5449. * Compute the transpose of the matrix
  5450. * @returns the new transposed matrix
  5451. */
  5452. Matrix.prototype.transpose = function () {
  5453. return Matrix.Transpose(this);
  5454. };
  5455. /**
  5456. * Compute the transpose of the matrix and store it in a given matrix
  5457. * @param result defines the target matrix
  5458. * @returns the current matrix
  5459. */
  5460. Matrix.prototype.transposeToRef = function (result) {
  5461. Matrix.TransposeToRef(this, result);
  5462. return this;
  5463. };
  5464. /**
  5465. * Sets the index-th row of the current matrix with the given 4 x float values
  5466. * @param index defines the row index
  5467. * @param x defines the x component to set
  5468. * @param y defines the y component to set
  5469. * @param z defines the z component to set
  5470. * @param w defines the w component to set
  5471. * @returns the updated current matrix
  5472. */
  5473. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5474. if (index < 0 || index > 3) {
  5475. return this;
  5476. }
  5477. var i = index * 4;
  5478. this.m[i + 0] = x;
  5479. this.m[i + 1] = y;
  5480. this.m[i + 2] = z;
  5481. this.m[i + 3] = w;
  5482. this._markAsUpdated();
  5483. return this;
  5484. };
  5485. /**
  5486. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5487. * @param scale defines the scale factor
  5488. * @returns a new matrix
  5489. */
  5490. Matrix.prototype.scale = function (scale) {
  5491. var result = new Matrix();
  5492. this.scaleToRef(scale, result);
  5493. return result;
  5494. };
  5495. /**
  5496. * Scale the current matrix values by a factor to a given result matrix
  5497. * @param scale defines the scale factor
  5498. * @param result defines the matrix to store the result
  5499. * @returns the current matrix
  5500. */
  5501. Matrix.prototype.scaleToRef = function (scale, result) {
  5502. for (var index = 0; index < 16; index++) {
  5503. result.m[index] = this.m[index] * scale;
  5504. }
  5505. result._markAsUpdated();
  5506. return this;
  5507. };
  5508. /**
  5509. * Scale the current matrix values by a factor and add the result to a given matrix
  5510. * @param scale defines the scale factor
  5511. * @param result defines the Matrix to store the result
  5512. * @returns the current matrix
  5513. */
  5514. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5515. for (var index = 0; index < 16; index++) {
  5516. result.m[index] += this.m[index] * scale;
  5517. }
  5518. result._markAsUpdated();
  5519. return this;
  5520. };
  5521. /**
  5522. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5523. * @param ref matrix to store the result
  5524. */
  5525. Matrix.prototype.toNormalMatrix = function (ref) {
  5526. this.invertToRef(ref);
  5527. ref.transpose();
  5528. var m = ref.m;
  5529. 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);
  5530. };
  5531. /**
  5532. * Gets only rotation part of the current matrix
  5533. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5534. */
  5535. Matrix.prototype.getRotationMatrix = function () {
  5536. var result = Matrix.Identity();
  5537. this.getRotationMatrixToRef(result);
  5538. return result;
  5539. };
  5540. /**
  5541. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5542. * @param result defines the target matrix to store data to
  5543. * @returns the current matrix
  5544. */
  5545. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5546. var m = this.m;
  5547. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5548. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5549. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5550. if (this.determinant() <= 0) {
  5551. sy *= -1;
  5552. }
  5553. if (sx === 0 || sy === 0 || sz === 0) {
  5554. Matrix.IdentityToRef(result);
  5555. }
  5556. else {
  5557. 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);
  5558. }
  5559. return this;
  5560. };
  5561. // Statics
  5562. /**
  5563. * Creates a matrix from an array
  5564. * @param array defines the source array
  5565. * @param offset defines an offset in the source array
  5566. * @returns a new Matrix set from the starting index of the given array
  5567. */
  5568. Matrix.FromArray = function (array, offset) {
  5569. var result = new Matrix();
  5570. if (!offset) {
  5571. offset = 0;
  5572. }
  5573. Matrix.FromArrayToRef(array, offset, result);
  5574. return result;
  5575. };
  5576. /**
  5577. * Copy the content of an array into a given matrix
  5578. * @param array defines the source array
  5579. * @param offset defines an offset in the source array
  5580. * @param result defines the target matrix
  5581. */
  5582. Matrix.FromArrayToRef = function (array, offset, result) {
  5583. for (var index = 0; index < 16; index++) {
  5584. result.m[index] = array[index + offset];
  5585. }
  5586. result._markAsUpdated();
  5587. };
  5588. /**
  5589. * Stores an array into a matrix after having multiplied each component by a given factor
  5590. * @param array defines the source array
  5591. * @param offset defines the offset in the source array
  5592. * @param scale defines the scaling factor
  5593. * @param result defines the target matrix
  5594. */
  5595. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5596. for (var index = 0; index < 16; index++) {
  5597. result.m[index] = array[index + offset] * scale;
  5598. }
  5599. result._markAsUpdated();
  5600. };
  5601. /**
  5602. * Stores a list of values (16) inside a given matrix
  5603. * @param initialM11 defines 1st value of 1st row
  5604. * @param initialM12 defines 2nd value of 1st row
  5605. * @param initialM13 defines 3rd value of 1st row
  5606. * @param initialM14 defines 4th value of 1st row
  5607. * @param initialM21 defines 1st value of 2nd row
  5608. * @param initialM22 defines 2nd value of 2nd row
  5609. * @param initialM23 defines 3rd value of 2nd row
  5610. * @param initialM24 defines 4th value of 2nd row
  5611. * @param initialM31 defines 1st value of 3rd row
  5612. * @param initialM32 defines 2nd value of 3rd row
  5613. * @param initialM33 defines 3rd value of 3rd row
  5614. * @param initialM34 defines 4th value of 3rd row
  5615. * @param initialM41 defines 1st value of 4th row
  5616. * @param initialM42 defines 2nd value of 4th row
  5617. * @param initialM43 defines 3rd value of 4th row
  5618. * @param initialM44 defines 4th value of 4th row
  5619. * @param result defines the target matrix
  5620. */
  5621. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5622. result.m[0] = initialM11;
  5623. result.m[1] = initialM12;
  5624. result.m[2] = initialM13;
  5625. result.m[3] = initialM14;
  5626. result.m[4] = initialM21;
  5627. result.m[5] = initialM22;
  5628. result.m[6] = initialM23;
  5629. result.m[7] = initialM24;
  5630. result.m[8] = initialM31;
  5631. result.m[9] = initialM32;
  5632. result.m[10] = initialM33;
  5633. result.m[11] = initialM34;
  5634. result.m[12] = initialM41;
  5635. result.m[13] = initialM42;
  5636. result.m[14] = initialM43;
  5637. result.m[15] = initialM44;
  5638. result._markAsUpdated();
  5639. };
  5640. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5641. /**
  5642. * Gets an identity matrix that must not be updated
  5643. */
  5644. get: function () {
  5645. return Matrix._identityReadOnly;
  5646. },
  5647. enumerable: true,
  5648. configurable: true
  5649. });
  5650. /**
  5651. * Creates new matrix from a list of values (16)
  5652. * @param initialM11 defines 1st value of 1st row
  5653. * @param initialM12 defines 2nd value of 1st row
  5654. * @param initialM13 defines 3rd value of 1st row
  5655. * @param initialM14 defines 4th value of 1st row
  5656. * @param initialM21 defines 1st value of 2nd row
  5657. * @param initialM22 defines 2nd value of 2nd row
  5658. * @param initialM23 defines 3rd value of 2nd row
  5659. * @param initialM24 defines 4th value of 2nd row
  5660. * @param initialM31 defines 1st value of 3rd row
  5661. * @param initialM32 defines 2nd value of 3rd row
  5662. * @param initialM33 defines 3rd value of 3rd row
  5663. * @param initialM34 defines 4th value of 3rd row
  5664. * @param initialM41 defines 1st value of 4th row
  5665. * @param initialM42 defines 2nd value of 4th row
  5666. * @param initialM43 defines 3rd value of 4th row
  5667. * @param initialM44 defines 4th value of 4th row
  5668. * @returns the new matrix
  5669. */
  5670. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5671. var result = new Matrix();
  5672. result.m[0] = initialM11;
  5673. result.m[1] = initialM12;
  5674. result.m[2] = initialM13;
  5675. result.m[3] = initialM14;
  5676. result.m[4] = initialM21;
  5677. result.m[5] = initialM22;
  5678. result.m[6] = initialM23;
  5679. result.m[7] = initialM24;
  5680. result.m[8] = initialM31;
  5681. result.m[9] = initialM32;
  5682. result.m[10] = initialM33;
  5683. result.m[11] = initialM34;
  5684. result.m[12] = initialM41;
  5685. result.m[13] = initialM42;
  5686. result.m[14] = initialM43;
  5687. result.m[15] = initialM44;
  5688. return result;
  5689. };
  5690. /**
  5691. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5692. * @param scale defines the scale vector3
  5693. * @param rotation defines the rotation quaternion
  5694. * @param translation defines the translation vector3
  5695. * @returns a new matrix
  5696. */
  5697. Matrix.Compose = function (scale, rotation, translation) {
  5698. var result = Matrix.Identity();
  5699. Matrix.ComposeToRef(scale, rotation, translation, result);
  5700. return result;
  5701. };
  5702. /**
  5703. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5704. * @param scale defines the scale vector3
  5705. * @param rotation defines the rotation quaternion
  5706. * @param translation defines the translation vector3
  5707. * @param result defines the target matrix
  5708. */
  5709. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5710. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5711. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5712. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5713. result.setTranslation(translation);
  5714. };
  5715. /**
  5716. * Creates a new identity matrix
  5717. * @returns a new identity matrix
  5718. */
  5719. Matrix.Identity = function () {
  5720. 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);
  5721. };
  5722. /**
  5723. * Creates a new identity matrix and stores the result in a given matrix
  5724. * @param result defines the target matrix
  5725. */
  5726. Matrix.IdentityToRef = function (result) {
  5727. 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);
  5728. };
  5729. /**
  5730. * Creates a new zero matrix
  5731. * @returns a new zero matrix
  5732. */
  5733. Matrix.Zero = function () {
  5734. 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);
  5735. };
  5736. /**
  5737. * Creates a new rotation matrix for "angle" radians around the X axis
  5738. * @param angle defines the angle (in radians) to use
  5739. * @return the new matrix
  5740. */
  5741. Matrix.RotationX = function (angle) {
  5742. var result = new Matrix();
  5743. Matrix.RotationXToRef(angle, result);
  5744. return result;
  5745. };
  5746. /**
  5747. * Creates a new matrix as the invert of a given matrix
  5748. * @param source defines the source matrix
  5749. * @returns the new matrix
  5750. */
  5751. Matrix.Invert = function (source) {
  5752. var result = new Matrix();
  5753. source.invertToRef(result);
  5754. return result;
  5755. };
  5756. /**
  5757. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5758. * @param angle defines the angle (in radians) to use
  5759. * @param result defines the target matrix
  5760. */
  5761. Matrix.RotationXToRef = function (angle, result) {
  5762. var s = Math.sin(angle);
  5763. var c = Math.cos(angle);
  5764. result.m[0] = 1.0;
  5765. result.m[15] = 1.0;
  5766. result.m[5] = c;
  5767. result.m[10] = c;
  5768. result.m[9] = -s;
  5769. result.m[6] = s;
  5770. result.m[1] = 0.0;
  5771. result.m[2] = 0.0;
  5772. result.m[3] = 0.0;
  5773. result.m[4] = 0.0;
  5774. result.m[7] = 0.0;
  5775. result.m[8] = 0.0;
  5776. result.m[11] = 0.0;
  5777. result.m[12] = 0.0;
  5778. result.m[13] = 0.0;
  5779. result.m[14] = 0.0;
  5780. result._markAsUpdated();
  5781. };
  5782. /**
  5783. * Creates a new rotation matrix for "angle" radians around the Y axis
  5784. * @param angle defines the angle (in radians) to use
  5785. * @return the new matrix
  5786. */
  5787. Matrix.RotationY = function (angle) {
  5788. var result = new Matrix();
  5789. Matrix.RotationYToRef(angle, result);
  5790. return result;
  5791. };
  5792. /**
  5793. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5794. * @param angle defines the angle (in radians) to use
  5795. * @param result defines the target matrix
  5796. */
  5797. Matrix.RotationYToRef = function (angle, result) {
  5798. var s = Math.sin(angle);
  5799. var c = Math.cos(angle);
  5800. result.m[5] = 1.0;
  5801. result.m[15] = 1.0;
  5802. result.m[0] = c;
  5803. result.m[2] = -s;
  5804. result.m[8] = s;
  5805. result.m[10] = c;
  5806. result.m[1] = 0.0;
  5807. result.m[3] = 0.0;
  5808. result.m[4] = 0.0;
  5809. result.m[6] = 0.0;
  5810. result.m[7] = 0.0;
  5811. result.m[9] = 0.0;
  5812. result.m[11] = 0.0;
  5813. result.m[12] = 0.0;
  5814. result.m[13] = 0.0;
  5815. result.m[14] = 0.0;
  5816. result._markAsUpdated();
  5817. };
  5818. /**
  5819. * Creates a new rotation matrix for "angle" radians around the Z axis
  5820. * @param angle defines the angle (in radians) to use
  5821. * @return the new matrix
  5822. */
  5823. Matrix.RotationZ = function (angle) {
  5824. var result = new Matrix();
  5825. Matrix.RotationZToRef(angle, result);
  5826. return result;
  5827. };
  5828. /**
  5829. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5830. * @param angle defines the angle (in radians) to use
  5831. * @param result defines the target matrix
  5832. */
  5833. Matrix.RotationZToRef = function (angle, result) {
  5834. var s = Math.sin(angle);
  5835. var c = Math.cos(angle);
  5836. result.m[10] = 1.0;
  5837. result.m[15] = 1.0;
  5838. result.m[0] = c;
  5839. result.m[1] = s;
  5840. result.m[4] = -s;
  5841. result.m[5] = c;
  5842. result.m[2] = 0.0;
  5843. result.m[3] = 0.0;
  5844. result.m[6] = 0.0;
  5845. result.m[7] = 0.0;
  5846. result.m[8] = 0.0;
  5847. result.m[9] = 0.0;
  5848. result.m[11] = 0.0;
  5849. result.m[12] = 0.0;
  5850. result.m[13] = 0.0;
  5851. result.m[14] = 0.0;
  5852. result._markAsUpdated();
  5853. };
  5854. /**
  5855. * Creates a new rotation matrix for "angle" radians around the given axis
  5856. * @param axis defines the axis to use
  5857. * @param angle defines the angle (in radians) to use
  5858. * @return the new matrix
  5859. */
  5860. Matrix.RotationAxis = function (axis, angle) {
  5861. var result = Matrix.Zero();
  5862. Matrix.RotationAxisToRef(axis, angle, result);
  5863. return result;
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @param result defines the target matrix
  5870. */
  5871. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5872. var s = Math.sin(-angle);
  5873. var c = Math.cos(-angle);
  5874. var c1 = 1 - c;
  5875. axis.normalize();
  5876. result.m[0] = (axis.x * axis.x) * c1 + c;
  5877. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5878. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5879. result.m[3] = 0.0;
  5880. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5881. result.m[5] = (axis.y * axis.y) * c1 + c;
  5882. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5883. result.m[7] = 0.0;
  5884. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5885. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5886. result.m[10] = (axis.z * axis.z) * c1 + c;
  5887. result.m[11] = 0.0;
  5888. result.m[15] = 1.0;
  5889. result._markAsUpdated();
  5890. };
  5891. /**
  5892. * Creates a rotation matrix
  5893. * @param yaw defines the yaw angle in radians (Y axis)
  5894. * @param pitch defines the pitch angle in radians (X axis)
  5895. * @param roll defines the roll angle in radians (X axis)
  5896. * @returns the new rotation matrix
  5897. */
  5898. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5899. var result = new Matrix();
  5900. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5901. return result;
  5902. };
  5903. /**
  5904. * Creates a rotation matrix and stores it in a given matrix
  5905. * @param yaw defines the yaw angle in radians (Y axis)
  5906. * @param pitch defines the pitch angle in radians (X axis)
  5907. * @param roll defines the roll angle in radians (X axis)
  5908. * @param result defines the target matrix
  5909. */
  5910. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5911. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5912. this._tempQuaternion.toRotationMatrix(result);
  5913. };
  5914. /**
  5915. * Creates a scaling matrix
  5916. * @param x defines the scale factor on X axis
  5917. * @param y defines the scale factor on Y axis
  5918. * @param z defines the scale factor on Z axis
  5919. * @returns the new matrix
  5920. */
  5921. Matrix.Scaling = function (x, y, z) {
  5922. var result = Matrix.Zero();
  5923. Matrix.ScalingToRef(x, y, z, result);
  5924. return result;
  5925. };
  5926. /**
  5927. * Creates a scaling matrix and stores it in a given matrix
  5928. * @param x defines the scale factor on X axis
  5929. * @param y defines the scale factor on Y axis
  5930. * @param z defines the scale factor on Z axis
  5931. * @param result defines the target matrix
  5932. */
  5933. Matrix.ScalingToRef = function (x, y, z, result) {
  5934. result.m[0] = x;
  5935. result.m[1] = 0.0;
  5936. result.m[2] = 0.0;
  5937. result.m[3] = 0.0;
  5938. result.m[4] = 0.0;
  5939. result.m[5] = y;
  5940. result.m[6] = 0.0;
  5941. result.m[7] = 0.0;
  5942. result.m[8] = 0.0;
  5943. result.m[9] = 0.0;
  5944. result.m[10] = z;
  5945. result.m[11] = 0.0;
  5946. result.m[12] = 0.0;
  5947. result.m[13] = 0.0;
  5948. result.m[14] = 0.0;
  5949. result.m[15] = 1.0;
  5950. result._markAsUpdated();
  5951. };
  5952. /**
  5953. * Creates a translation matrix
  5954. * @param x defines the translation on X axis
  5955. * @param y defines the translation on Y axis
  5956. * @param z defines the translationon Z axis
  5957. * @returns the new matrix
  5958. */
  5959. Matrix.Translation = function (x, y, z) {
  5960. var result = Matrix.Identity();
  5961. Matrix.TranslationToRef(x, y, z, result);
  5962. return result;
  5963. };
  5964. /**
  5965. * Creates a translation matrix and stores it in a given matrix
  5966. * @param x defines the translation on X axis
  5967. * @param y defines the translation on Y axis
  5968. * @param z defines the translationon Z axis
  5969. * @param result defines the target matrix
  5970. */
  5971. Matrix.TranslationToRef = function (x, y, z, result) {
  5972. 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);
  5973. };
  5974. /**
  5975. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5976. * @param startValue defines the start value
  5977. * @param endValue defines the end value
  5978. * @param gradient defines the gradient factor
  5979. * @returns the new matrix
  5980. */
  5981. Matrix.Lerp = function (startValue, endValue, gradient) {
  5982. var result = Matrix.Zero();
  5983. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5984. return result;
  5985. };
  5986. /**
  5987. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5988. * @param startValue defines the start value
  5989. * @param endValue defines the end value
  5990. * @param gradient defines the gradient factor
  5991. * @param result defines the Matrix object where to store data
  5992. */
  5993. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5994. for (var index = 0; index < 16; index++) {
  5995. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5996. }
  5997. result._markAsUpdated();
  5998. };
  5999. /**
  6000. * Builds a new matrix whose values are computed by:
  6001. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6002. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6003. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6004. * @param startValue defines the first matrix
  6005. * @param endValue defines the second matrix
  6006. * @param gradient defines the gradient between the two matrices
  6007. * @returns the new matrix
  6008. */
  6009. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6010. var result = Matrix.Zero();
  6011. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6012. return result;
  6013. };
  6014. /**
  6015. * Update a matrix to values which are computed by:
  6016. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6017. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6018. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6019. * @param startValue defines the first matrix
  6020. * @param endValue defines the second matrix
  6021. * @param gradient defines the gradient between the two matrices
  6022. * @param result defines the target matrix
  6023. */
  6024. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6025. var startScale = MathTmp.Vector3[0];
  6026. var startRotation = MathTmp.Quaternion[0];
  6027. var startTranslation = MathTmp.Vector3[1];
  6028. startValue.decompose(startScale, startRotation, startTranslation);
  6029. var endScale = MathTmp.Vector3[2];
  6030. var endRotation = MathTmp.Quaternion[1];
  6031. var endTranslation = MathTmp.Vector3[3];
  6032. endValue.decompose(endScale, endRotation, endTranslation);
  6033. var resultScale = MathTmp.Vector3[4];
  6034. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6035. var resultRotation = MathTmp.Quaternion[2];
  6036. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6037. var resultTranslation = MathTmp.Vector3[5];
  6038. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6039. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6040. };
  6041. /**
  6042. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6043. * This function works in left handed mode
  6044. * @param eye defines the final position of the entity
  6045. * @param target defines where the entity should look at
  6046. * @param up defines the up vector for the entity
  6047. * @returns the new matrix
  6048. */
  6049. Matrix.LookAtLH = function (eye, target, up) {
  6050. var result = Matrix.Zero();
  6051. Matrix.LookAtLHToRef(eye, target, up, result);
  6052. return result;
  6053. };
  6054. /**
  6055. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6056. * This function works in left handed mode
  6057. * @param eye defines the final position of the entity
  6058. * @param target defines where the entity should look at
  6059. * @param up defines the up vector for the entity
  6060. * @param result defines the target matrix
  6061. */
  6062. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6063. // Z axis
  6064. target.subtractToRef(eye, this._zAxis);
  6065. this._zAxis.normalize();
  6066. // X axis
  6067. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6068. if (this._xAxis.lengthSquared() === 0) {
  6069. this._xAxis.x = 1.0;
  6070. }
  6071. else {
  6072. this._xAxis.normalize();
  6073. }
  6074. // Y axis
  6075. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6076. this._yAxis.normalize();
  6077. // Eye angles
  6078. var ex = -Vector3.Dot(this._xAxis, eye);
  6079. var ey = -Vector3.Dot(this._yAxis, eye);
  6080. var ez = -Vector3.Dot(this._zAxis, eye);
  6081. 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);
  6082. };
  6083. /**
  6084. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6085. * This function works in right handed mode
  6086. * @param eye defines the final position of the entity
  6087. * @param target defines where the entity should look at
  6088. * @param up defines the up vector for the entity
  6089. * @returns the new matrix
  6090. */
  6091. Matrix.LookAtRH = function (eye, target, up) {
  6092. var result = Matrix.Zero();
  6093. Matrix.LookAtRHToRef(eye, target, up, result);
  6094. return result;
  6095. };
  6096. /**
  6097. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6098. * This function works in right handed mode
  6099. * @param eye defines the final position of the entity
  6100. * @param target defines where the entity should look at
  6101. * @param up defines the up vector for the entity
  6102. * @param result defines the target matrix
  6103. */
  6104. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6105. // Z axis
  6106. eye.subtractToRef(target, this._zAxis);
  6107. this._zAxis.normalize();
  6108. // X axis
  6109. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6110. if (this._xAxis.lengthSquared() === 0) {
  6111. this._xAxis.x = 1.0;
  6112. }
  6113. else {
  6114. this._xAxis.normalize();
  6115. }
  6116. // Y axis
  6117. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6118. this._yAxis.normalize();
  6119. // Eye angles
  6120. var ex = -Vector3.Dot(this._xAxis, eye);
  6121. var ey = -Vector3.Dot(this._yAxis, eye);
  6122. var ez = -Vector3.Dot(this._zAxis, eye);
  6123. 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);
  6124. };
  6125. /**
  6126. * Create a left-handed orthographic projection matrix
  6127. * @param width defines the viewport width
  6128. * @param height defines the viewport height
  6129. * @param znear defines the near clip plane
  6130. * @param zfar defines the far clip plane
  6131. * @returns a new matrix as a left-handed orthographic projection matrix
  6132. */
  6133. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6134. var matrix = Matrix.Zero();
  6135. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6136. return matrix;
  6137. };
  6138. /**
  6139. * Store a left-handed orthographic projection to a given matrix
  6140. * @param width defines the viewport width
  6141. * @param height defines the viewport height
  6142. * @param znear defines the near clip plane
  6143. * @param zfar defines the far clip plane
  6144. * @param result defines the target matrix
  6145. */
  6146. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6147. var n = znear;
  6148. var f = zfar;
  6149. var a = 2.0 / width;
  6150. var b = 2.0 / height;
  6151. var c = 2.0 / (f - n);
  6152. var d = -(f + n) / (f - n);
  6153. 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);
  6154. };
  6155. /**
  6156. * Create a left-handed orthographic projection matrix
  6157. * @param left defines the viewport left coordinate
  6158. * @param right defines the viewport right coordinate
  6159. * @param bottom defines the viewport bottom coordinate
  6160. * @param top defines the viewport top coordinate
  6161. * @param znear defines the near clip plane
  6162. * @param zfar defines the far clip plane
  6163. * @returns a new matrix as a left-handed orthographic projection matrix
  6164. */
  6165. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6166. var matrix = Matrix.Zero();
  6167. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6168. return matrix;
  6169. };
  6170. /**
  6171. * Stores a left-handed orthographic projection into a given matrix
  6172. * @param left defines the viewport left coordinate
  6173. * @param right defines the viewport right coordinate
  6174. * @param bottom defines the viewport bottom coordinate
  6175. * @param top defines the viewport top coordinate
  6176. * @param znear defines the near clip plane
  6177. * @param zfar defines the far clip plane
  6178. * @param result defines the target matrix
  6179. */
  6180. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6181. var n = znear;
  6182. var f = zfar;
  6183. var a = 2.0 / (right - left);
  6184. var b = 2.0 / (top - bottom);
  6185. var c = 2.0 / (f - n);
  6186. var d = -(f + n) / (f - n);
  6187. var i0 = (left + right) / (left - right);
  6188. var i1 = (top + bottom) / (bottom - top);
  6189. 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);
  6190. };
  6191. /**
  6192. * Creates a right-handed orthographic projection matrix
  6193. * @param left defines the viewport left coordinate
  6194. * @param right defines the viewport right coordinate
  6195. * @param bottom defines the viewport bottom coordinate
  6196. * @param top defines the viewport top coordinate
  6197. * @param znear defines the near clip plane
  6198. * @param zfar defines the far clip plane
  6199. * @returns a new matrix as a right-handed orthographic projection matrix
  6200. */
  6201. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6202. var matrix = Matrix.Zero();
  6203. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6204. return matrix;
  6205. };
  6206. /**
  6207. * Stores a right-handed orthographic projection into a given matrix
  6208. * @param left defines the viewport left coordinate
  6209. * @param right defines the viewport right coordinate
  6210. * @param bottom defines the viewport bottom coordinate
  6211. * @param top defines the viewport top coordinate
  6212. * @param znear defines the near clip plane
  6213. * @param zfar defines the far clip plane
  6214. * @param result defines the target matrix
  6215. */
  6216. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6217. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6218. result.m[10] *= -1.0;
  6219. };
  6220. /**
  6221. * Creates a left-handed perspective projection matrix
  6222. * @param width defines the viewport width
  6223. * @param height defines the viewport height
  6224. * @param znear defines the near clip plane
  6225. * @param zfar defines the far clip plane
  6226. * @returns a new matrix as a left-handed perspective projection matrix
  6227. */
  6228. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6229. var matrix = Matrix.Zero();
  6230. var n = znear;
  6231. var f = zfar;
  6232. var a = 2.0 * n / width;
  6233. var b = 2.0 * n / height;
  6234. var c = (f + n) / (f - n);
  6235. var d = -2.0 * f * n / (f - n);
  6236. 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);
  6237. return matrix;
  6238. };
  6239. /**
  6240. * Creates a left-handed perspective projection matrix
  6241. * @param fov defines the horizontal field of view
  6242. * @param aspect defines the aspect ratio
  6243. * @param znear defines the near clip plane
  6244. * @param zfar defines the far clip plane
  6245. * @returns a new matrix as a left-handed perspective projection matrix
  6246. */
  6247. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6248. var matrix = Matrix.Zero();
  6249. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6250. return matrix;
  6251. };
  6252. /**
  6253. * Stores a left-handed perspective projection into a given matrix
  6254. * @param fov defines the horizontal field of view
  6255. * @param aspect defines the aspect ratio
  6256. * @param znear defines the near clip plane
  6257. * @param zfar defines the far clip plane
  6258. * @param result defines the target matrix
  6259. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6260. */
  6261. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6262. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6263. var n = znear;
  6264. var f = zfar;
  6265. var t = 1.0 / (Math.tan(fov * 0.5));
  6266. var a = isVerticalFovFixed ? (t / aspect) : t;
  6267. var b = isVerticalFovFixed ? t : (t * aspect);
  6268. var c = (f + n) / (f - n);
  6269. var d = -2.0 * f * n / (f - n);
  6270. 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);
  6271. };
  6272. /**
  6273. * Creates a right-handed perspective projection matrix
  6274. * @param fov defines the horizontal field of view
  6275. * @param aspect defines the aspect ratio
  6276. * @param znear defines the near clip plane
  6277. * @param zfar defines the far clip plane
  6278. * @returns a new matrix as a right-handed perspective projection matrix
  6279. */
  6280. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6281. var matrix = Matrix.Zero();
  6282. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6283. return matrix;
  6284. };
  6285. /**
  6286. * Stores a right-handed perspective projection into a given matrix
  6287. * @param fov defines the horizontal field of view
  6288. * @param aspect defines the aspect ratio
  6289. * @param znear defines the near clip plane
  6290. * @param zfar defines the far clip plane
  6291. * @param result defines the target matrix
  6292. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6293. */
  6294. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6295. //alternatively this could be expressed as:
  6296. // m = PerspectiveFovLHToRef
  6297. // m[10] *= -1.0;
  6298. // m[11] *= -1.0;
  6299. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6300. var n = znear;
  6301. var f = zfar;
  6302. var t = 1.0 / (Math.tan(fov * 0.5));
  6303. var a = isVerticalFovFixed ? (t / aspect) : t;
  6304. var b = isVerticalFovFixed ? t : (t * aspect);
  6305. var c = -(f + n) / (f - n);
  6306. var d = -2 * f * n / (f - n);
  6307. 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);
  6308. };
  6309. /**
  6310. * Stores a perspective projection for WebVR info a given matrix
  6311. * @param fov defines the field of view
  6312. * @param znear defines the near clip plane
  6313. * @param zfar defines the far clip plane
  6314. * @param result defines the target matrix
  6315. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6316. */
  6317. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6318. if (rightHanded === void 0) { rightHanded = false; }
  6319. var rightHandedFactor = rightHanded ? -1 : 1;
  6320. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6321. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6322. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6323. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6324. var xScale = 2.0 / (leftTan + rightTan);
  6325. var yScale = 2.0 / (upTan + downTan);
  6326. result.m[0] = xScale;
  6327. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6328. result.m[5] = yScale;
  6329. result.m[6] = result.m[7] = 0.0;
  6330. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6331. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6332. result.m[10] = -zfar / (znear - zfar);
  6333. result.m[11] = 1.0 * rightHandedFactor;
  6334. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6335. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6336. result._markAsUpdated();
  6337. };
  6338. /**
  6339. * Computes a complete transformation matrix
  6340. * @param viewport defines the viewport to use
  6341. * @param world defines the world matrix
  6342. * @param view defines the view matrix
  6343. * @param projection defines the projection matrix
  6344. * @param zmin defines the near clip plane
  6345. * @param zmax defines the far clip plane
  6346. * @returns the transformation matrix
  6347. */
  6348. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6349. var cw = viewport.width;
  6350. var ch = viewport.height;
  6351. var cx = viewport.x;
  6352. var cy = viewport.y;
  6353. 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);
  6354. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6355. };
  6356. /**
  6357. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6358. * @param matrix defines the matrix to use
  6359. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6360. */
  6361. Matrix.GetAsMatrix2x2 = function (matrix) {
  6362. return new Float32Array([
  6363. matrix.m[0], matrix.m[1],
  6364. matrix.m[4], matrix.m[5]
  6365. ]);
  6366. };
  6367. /**
  6368. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix3x3 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1], matrix.m[2],
  6375. matrix.m[4], matrix.m[5], matrix.m[6],
  6376. matrix.m[8], matrix.m[9], matrix.m[10]
  6377. ]);
  6378. };
  6379. /**
  6380. * Compute the transpose of a given matrix
  6381. * @param matrix defines the matrix to transpose
  6382. * @returns the new matrix
  6383. */
  6384. Matrix.Transpose = function (matrix) {
  6385. var result = new Matrix();
  6386. Matrix.TransposeToRef(matrix, result);
  6387. return result;
  6388. };
  6389. /**
  6390. * Compute the transpose of a matrix and store it in a target matrix
  6391. * @param matrix defines the matrix to transpose
  6392. * @param result defines the target matrix
  6393. */
  6394. Matrix.TransposeToRef = function (matrix, result) {
  6395. result.m[0] = matrix.m[0];
  6396. result.m[1] = matrix.m[4];
  6397. result.m[2] = matrix.m[8];
  6398. result.m[3] = matrix.m[12];
  6399. result.m[4] = matrix.m[1];
  6400. result.m[5] = matrix.m[5];
  6401. result.m[6] = matrix.m[9];
  6402. result.m[7] = matrix.m[13];
  6403. result.m[8] = matrix.m[2];
  6404. result.m[9] = matrix.m[6];
  6405. result.m[10] = matrix.m[10];
  6406. result.m[11] = matrix.m[14];
  6407. result.m[12] = matrix.m[3];
  6408. result.m[13] = matrix.m[7];
  6409. result.m[14] = matrix.m[11];
  6410. result.m[15] = matrix.m[15];
  6411. };
  6412. /**
  6413. * Computes a reflection matrix from a plane
  6414. * @param plane defines the reflection plane
  6415. * @returns a new matrix
  6416. */
  6417. Matrix.Reflection = function (plane) {
  6418. var matrix = new Matrix();
  6419. Matrix.ReflectionToRef(plane, matrix);
  6420. return matrix;
  6421. };
  6422. /**
  6423. * Computes a reflection matrix from a plane
  6424. * @param plane defines the reflection plane
  6425. * @param result defines the target matrix
  6426. */
  6427. Matrix.ReflectionToRef = function (plane, result) {
  6428. plane.normalize();
  6429. var x = plane.normal.x;
  6430. var y = plane.normal.y;
  6431. var z = plane.normal.z;
  6432. var temp = -2 * x;
  6433. var temp2 = -2 * y;
  6434. var temp3 = -2 * z;
  6435. result.m[0] = (temp * x) + 1;
  6436. result.m[1] = temp2 * x;
  6437. result.m[2] = temp3 * x;
  6438. result.m[3] = 0.0;
  6439. result.m[4] = temp * y;
  6440. result.m[5] = (temp2 * y) + 1;
  6441. result.m[6] = temp3 * y;
  6442. result.m[7] = 0.0;
  6443. result.m[8] = temp * z;
  6444. result.m[9] = temp2 * z;
  6445. result.m[10] = (temp3 * z) + 1;
  6446. result.m[11] = 0.0;
  6447. result.m[12] = temp * plane.d;
  6448. result.m[13] = temp2 * plane.d;
  6449. result.m[14] = temp3 * plane.d;
  6450. result.m[15] = 1.0;
  6451. result._markAsUpdated();
  6452. };
  6453. /**
  6454. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6455. * @param xaxis defines the value of the 1st axis
  6456. * @param yaxis defines the value of the 2nd axis
  6457. * @param zaxis defines the value of the 3rd axis
  6458. * @param result defines the target matrix
  6459. */
  6460. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6461. result.m[0] = xaxis.x;
  6462. result.m[1] = xaxis.y;
  6463. result.m[2] = xaxis.z;
  6464. result.m[3] = 0.0;
  6465. result.m[4] = yaxis.x;
  6466. result.m[5] = yaxis.y;
  6467. result.m[6] = yaxis.z;
  6468. result.m[7] = 0.0;
  6469. result.m[8] = zaxis.x;
  6470. result.m[9] = zaxis.y;
  6471. result.m[10] = zaxis.z;
  6472. result.m[11] = 0.0;
  6473. result.m[12] = 0.0;
  6474. result.m[13] = 0.0;
  6475. result.m[14] = 0.0;
  6476. result.m[15] = 1.0;
  6477. result._markAsUpdated();
  6478. };
  6479. /**
  6480. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6481. * @param quat defines the quaternion to use
  6482. * @param result defines the target matrix
  6483. */
  6484. Matrix.FromQuaternionToRef = function (quat, result) {
  6485. var xx = quat.x * quat.x;
  6486. var yy = quat.y * quat.y;
  6487. var zz = quat.z * quat.z;
  6488. var xy = quat.x * quat.y;
  6489. var zw = quat.z * quat.w;
  6490. var zx = quat.z * quat.x;
  6491. var yw = quat.y * quat.w;
  6492. var yz = quat.y * quat.z;
  6493. var xw = quat.x * quat.w;
  6494. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6495. result.m[1] = 2.0 * (xy + zw);
  6496. result.m[2] = 2.0 * (zx - yw);
  6497. result.m[3] = 0.0;
  6498. result.m[4] = 2.0 * (xy - zw);
  6499. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6500. result.m[6] = 2.0 * (yz + xw);
  6501. result.m[7] = 0.0;
  6502. result.m[8] = 2.0 * (zx + yw);
  6503. result.m[9] = 2.0 * (yz - xw);
  6504. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6505. result.m[11] = 0.0;
  6506. result.m[12] = 0.0;
  6507. result.m[13] = 0.0;
  6508. result.m[14] = 0.0;
  6509. result.m[15] = 1.0;
  6510. result._markAsUpdated();
  6511. };
  6512. Matrix._tempQuaternion = new Quaternion();
  6513. Matrix._xAxis = Vector3.Zero();
  6514. Matrix._yAxis = Vector3.Zero();
  6515. Matrix._zAxis = Vector3.Zero();
  6516. Matrix._updateFlagSeed = 0;
  6517. Matrix._identityReadOnly = Matrix.Identity();
  6518. return Matrix;
  6519. }());
  6520. BABYLON.Matrix = Matrix;
  6521. var Plane = /** @class */ (function () {
  6522. /**
  6523. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6524. */
  6525. function Plane(a, b, c, d) {
  6526. this.normal = new Vector3(a, b, c);
  6527. this.d = d;
  6528. }
  6529. /**
  6530. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6531. */
  6532. Plane.prototype.asArray = function () {
  6533. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6534. };
  6535. // Methods
  6536. /**
  6537. * Returns a new plane copied from the current Plane.
  6538. */
  6539. Plane.prototype.clone = function () {
  6540. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6541. };
  6542. /**
  6543. * Returns the string "Plane".
  6544. */
  6545. Plane.prototype.getClassName = function () {
  6546. return "Plane";
  6547. };
  6548. /**
  6549. * Returns the Plane hash code.
  6550. */
  6551. Plane.prototype.getHashCode = function () {
  6552. var hash = this.normal.getHashCode();
  6553. hash = (hash * 397) ^ (this.d || 0);
  6554. return hash;
  6555. };
  6556. /**
  6557. * Normalize the current Plane in place.
  6558. * Returns the updated Plane.
  6559. */
  6560. Plane.prototype.normalize = function () {
  6561. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6562. var magnitude = 0.0;
  6563. if (norm !== 0) {
  6564. magnitude = 1.0 / norm;
  6565. }
  6566. this.normal.x *= magnitude;
  6567. this.normal.y *= magnitude;
  6568. this.normal.z *= magnitude;
  6569. this.d *= magnitude;
  6570. return this;
  6571. };
  6572. /**
  6573. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6574. */
  6575. Plane.prototype.transform = function (transformation) {
  6576. var transposedMatrix = Matrix.Transpose(transformation);
  6577. var x = this.normal.x;
  6578. var y = this.normal.y;
  6579. var z = this.normal.z;
  6580. var d = this.d;
  6581. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6582. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6583. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6584. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6585. return new Plane(normalX, normalY, normalZ, finalD);
  6586. };
  6587. /**
  6588. * Returns the dot product (float) of the point coordinates and the plane normal.
  6589. */
  6590. Plane.prototype.dotCoordinate = function (point) {
  6591. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6592. };
  6593. /**
  6594. * Updates the current Plane from the plane defined by the three given points.
  6595. * Returns the updated Plane.
  6596. */
  6597. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6598. var x1 = point2.x - point1.x;
  6599. var y1 = point2.y - point1.y;
  6600. var z1 = point2.z - point1.z;
  6601. var x2 = point3.x - point1.x;
  6602. var y2 = point3.y - point1.y;
  6603. var z2 = point3.z - point1.z;
  6604. var yz = (y1 * z2) - (z1 * y2);
  6605. var xz = (z1 * x2) - (x1 * z2);
  6606. var xy = (x1 * y2) - (y1 * x2);
  6607. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6608. var invPyth;
  6609. if (pyth !== 0) {
  6610. invPyth = 1.0 / pyth;
  6611. }
  6612. else {
  6613. invPyth = 0.0;
  6614. }
  6615. this.normal.x = yz * invPyth;
  6616. this.normal.y = xz * invPyth;
  6617. this.normal.z = xy * invPyth;
  6618. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6619. return this;
  6620. };
  6621. /**
  6622. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6623. */
  6624. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6625. var dot = Vector3.Dot(this.normal, direction);
  6626. return (dot <= epsilon);
  6627. };
  6628. /**
  6629. * Returns the signed distance (float) from the given point to the Plane.
  6630. */
  6631. Plane.prototype.signedDistanceTo = function (point) {
  6632. return Vector3.Dot(point, this.normal) + this.d;
  6633. };
  6634. // Statics
  6635. /**
  6636. * Returns a new Plane from the given array.
  6637. */
  6638. Plane.FromArray = function (array) {
  6639. return new Plane(array[0], array[1], array[2], array[3]);
  6640. };
  6641. /**
  6642. * Returns a new Plane defined by the three given points.
  6643. */
  6644. Plane.FromPoints = function (point1, point2, point3) {
  6645. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6646. result.copyFromPoints(point1, point2, point3);
  6647. return result;
  6648. };
  6649. /**
  6650. * Returns a new Plane the normal vector to this plane at the given origin point.
  6651. * Note : the vector "normal" is updated because normalized.
  6652. */
  6653. Plane.FromPositionAndNormal = function (origin, normal) {
  6654. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6655. normal.normalize();
  6656. result.normal = normal;
  6657. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6662. */
  6663. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6664. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6665. return Vector3.Dot(point, normal) + d;
  6666. };
  6667. return Plane;
  6668. }());
  6669. BABYLON.Plane = Plane;
  6670. var Viewport = /** @class */ (function () {
  6671. /**
  6672. * Creates a Viewport object located at (x, y) and sized (width, height).
  6673. */
  6674. function Viewport(x, y, width, height) {
  6675. this.x = x;
  6676. this.y = y;
  6677. this.width = width;
  6678. this.height = height;
  6679. }
  6680. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6681. if (renderWidthOrEngine.getRenderWidth) {
  6682. var engine = renderWidthOrEngine;
  6683. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6684. }
  6685. var renderWidth = renderWidthOrEngine;
  6686. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6687. };
  6688. /**
  6689. * Returns a new Viewport copied from the current one.
  6690. */
  6691. Viewport.prototype.clone = function () {
  6692. return new Viewport(this.x, this.y, this.width, this.height);
  6693. };
  6694. return Viewport;
  6695. }());
  6696. BABYLON.Viewport = Viewport;
  6697. var Frustum = /** @class */ (function () {
  6698. function Frustum() {
  6699. }
  6700. /**
  6701. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6702. */
  6703. Frustum.GetPlanes = function (transform) {
  6704. var frustumPlanes = [];
  6705. for (var index = 0; index < 6; index++) {
  6706. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6707. }
  6708. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6709. return frustumPlanes;
  6710. };
  6711. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6712. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6713. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6714. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6715. frustumPlane.d = transform.m[15] + transform.m[14];
  6716. frustumPlane.normalize();
  6717. };
  6718. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6719. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6720. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6721. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6722. frustumPlane.d = transform.m[15] - transform.m[14];
  6723. frustumPlane.normalize();
  6724. };
  6725. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6726. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6727. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6728. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6729. frustumPlane.d = transform.m[15] + transform.m[12];
  6730. frustumPlane.normalize();
  6731. };
  6732. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6733. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6734. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6735. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6736. frustumPlane.d = transform.m[15] - transform.m[12];
  6737. frustumPlane.normalize();
  6738. };
  6739. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6740. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6741. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6742. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6743. frustumPlane.d = transform.m[15] - transform.m[13];
  6744. frustumPlane.normalize();
  6745. };
  6746. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6747. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6748. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6749. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6750. frustumPlane.d = transform.m[15] + transform.m[13];
  6751. frustumPlane.normalize();
  6752. };
  6753. /**
  6754. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6755. */
  6756. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6757. // Near
  6758. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6759. // Far
  6760. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6761. // Left
  6762. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6763. // Right
  6764. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6765. // Top
  6766. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6767. // Bottom
  6768. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6769. };
  6770. return Frustum;
  6771. }());
  6772. BABYLON.Frustum = Frustum;
  6773. /** Defines supported spaces */
  6774. var Space;
  6775. (function (Space) {
  6776. /** Local (object) space */
  6777. Space[Space["LOCAL"] = 0] = "LOCAL";
  6778. /** World space */
  6779. Space[Space["WORLD"] = 1] = "WORLD";
  6780. /** Bone space */
  6781. Space[Space["BONE"] = 2] = "BONE";
  6782. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6783. /** Defines the 3 main axes */
  6784. var Axis = /** @class */ (function () {
  6785. function Axis() {
  6786. }
  6787. /** X axis */
  6788. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6789. /** Y axis */
  6790. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6791. /** Z axis */
  6792. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6793. return Axis;
  6794. }());
  6795. BABYLON.Axis = Axis;
  6796. ;
  6797. var BezierCurve = /** @class */ (function () {
  6798. function BezierCurve() {
  6799. }
  6800. /**
  6801. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6802. */
  6803. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6804. // Extract X (which is equal to time here)
  6805. var f0 = 1 - 3 * x2 + 3 * x1;
  6806. var f1 = 3 * x2 - 6 * x1;
  6807. var f2 = 3 * x1;
  6808. var refinedT = t;
  6809. for (var i = 0; i < 5; i++) {
  6810. var refinedT2 = refinedT * refinedT;
  6811. var refinedT3 = refinedT2 * refinedT;
  6812. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6813. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6814. refinedT -= (x - t) * slope;
  6815. refinedT = Math.min(1, Math.max(0, refinedT));
  6816. }
  6817. // Resolve cubic bezier for the given x
  6818. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6819. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6820. Math.pow(refinedT, 3);
  6821. };
  6822. return BezierCurve;
  6823. }());
  6824. BABYLON.BezierCurve = BezierCurve;
  6825. /**
  6826. * Defines potential orientation for back face culling
  6827. */
  6828. var Orientation;
  6829. (function (Orientation) {
  6830. /**
  6831. * Clockwise
  6832. */
  6833. Orientation[Orientation["CW"] = 0] = "CW";
  6834. /** Counter clockwise */
  6835. Orientation[Orientation["CCW"] = 1] = "CCW";
  6836. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6837. /**
  6838. * Defines angle representation
  6839. */
  6840. var Angle = /** @class */ (function () {
  6841. /**
  6842. * Creates an Angle object of "radians" radians (float).
  6843. */
  6844. function Angle(radians) {
  6845. this._radians = radians;
  6846. if (this._radians < 0.0)
  6847. this._radians += (2.0 * Math.PI);
  6848. }
  6849. /**
  6850. * Get value in degrees
  6851. * @returns the Angle value in degrees (float)
  6852. */
  6853. Angle.prototype.degrees = function () {
  6854. return this._radians * 180.0 / Math.PI;
  6855. };
  6856. /**
  6857. * Get value in radians
  6858. * @returns the Angle value in radians (float)
  6859. */
  6860. Angle.prototype.radians = function () {
  6861. return this._radians;
  6862. };
  6863. /**
  6864. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6865. * @param a defines first vector
  6866. * @param b defines second vector
  6867. * @returns a new Angle
  6868. */
  6869. Angle.BetweenTwoPoints = function (a, b) {
  6870. var delta = b.subtract(a);
  6871. var theta = Math.atan2(delta.y, delta.x);
  6872. return new Angle(theta);
  6873. };
  6874. /**
  6875. * Gets a new Angle object from the given float in radians
  6876. * @param radians defines the angle value in radians
  6877. * @returns a new Angle
  6878. */
  6879. Angle.FromRadians = function (radians) {
  6880. return new Angle(radians);
  6881. };
  6882. /**
  6883. * Gets a new Angle object from the given float in degrees
  6884. * @param degrees defines the angle value in degrees
  6885. * @returns a new Angle
  6886. */
  6887. Angle.FromDegrees = function (degrees) {
  6888. return new Angle(degrees * Math.PI / 180.0);
  6889. };
  6890. return Angle;
  6891. }());
  6892. BABYLON.Angle = Angle;
  6893. var Arc2 = /** @class */ (function () {
  6894. /**
  6895. * Creates an Arc object from the three given points : start, middle and end.
  6896. */
  6897. function Arc2(startPoint, midPoint, endPoint) {
  6898. this.startPoint = startPoint;
  6899. this.midPoint = midPoint;
  6900. this.endPoint = endPoint;
  6901. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6902. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6903. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6904. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6905. 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);
  6906. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6907. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6908. var a1 = this.startAngle.degrees();
  6909. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6910. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6911. // angles correction
  6912. if (a2 - a1 > +180.0)
  6913. a2 -= 360.0;
  6914. if (a2 - a1 < -180.0)
  6915. a2 += 360.0;
  6916. if (a3 - a2 > +180.0)
  6917. a3 -= 360.0;
  6918. if (a3 - a2 < -180.0)
  6919. a3 += 360.0;
  6920. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6921. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6922. }
  6923. return Arc2;
  6924. }());
  6925. BABYLON.Arc2 = Arc2;
  6926. var Path2 = /** @class */ (function () {
  6927. /**
  6928. * Creates a Path2 object from the starting 2D coordinates x and y.
  6929. */
  6930. function Path2(x, y) {
  6931. this._points = new Array();
  6932. this._length = 0.0;
  6933. this.closed = false;
  6934. this._points.push(new Vector2(x, y));
  6935. }
  6936. /**
  6937. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6938. * Returns the updated Path2.
  6939. */
  6940. Path2.prototype.addLineTo = function (x, y) {
  6941. if (this.closed) {
  6942. return this;
  6943. }
  6944. var newPoint = new Vector2(x, y);
  6945. var previousPoint = this._points[this._points.length - 1];
  6946. this._points.push(newPoint);
  6947. this._length += newPoint.subtract(previousPoint).length();
  6948. return this;
  6949. };
  6950. /**
  6951. * 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.
  6952. * Returns the updated Path2.
  6953. */
  6954. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6955. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6956. if (this.closed) {
  6957. return this;
  6958. }
  6959. var startPoint = this._points[this._points.length - 1];
  6960. var midPoint = new Vector2(midX, midY);
  6961. var endPoint = new Vector2(endX, endY);
  6962. var arc = new Arc2(startPoint, midPoint, endPoint);
  6963. var increment = arc.angle.radians() / numberOfSegments;
  6964. if (arc.orientation === Orientation.CW)
  6965. increment *= -1;
  6966. var currentAngle = arc.startAngle.radians() + increment;
  6967. for (var i = 0; i < numberOfSegments; i++) {
  6968. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6969. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6970. this.addLineTo(x, y);
  6971. currentAngle += increment;
  6972. }
  6973. return this;
  6974. };
  6975. /**
  6976. * Closes the Path2.
  6977. * Returns the Path2.
  6978. */
  6979. Path2.prototype.close = function () {
  6980. this.closed = true;
  6981. return this;
  6982. };
  6983. /**
  6984. * Returns the Path2 total length (float).
  6985. */
  6986. Path2.prototype.length = function () {
  6987. var result = this._length;
  6988. if (!this.closed) {
  6989. var lastPoint = this._points[this._points.length - 1];
  6990. var firstPoint = this._points[0];
  6991. result += (firstPoint.subtract(lastPoint).length());
  6992. }
  6993. return result;
  6994. };
  6995. /**
  6996. * Returns the Path2 internal array of points.
  6997. */
  6998. Path2.prototype.getPoints = function () {
  6999. return this._points;
  7000. };
  7001. /**
  7002. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7003. */
  7004. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7005. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7006. return Vector2.Zero();
  7007. }
  7008. var lengthPosition = normalizedLengthPosition * this.length();
  7009. var previousOffset = 0;
  7010. for (var i = 0; i < this._points.length; i++) {
  7011. var j = (i + 1) % this._points.length;
  7012. var a = this._points[i];
  7013. var b = this._points[j];
  7014. var bToA = b.subtract(a);
  7015. var nextOffset = (bToA.length() + previousOffset);
  7016. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7017. var dir = bToA.normalize();
  7018. var localOffset = lengthPosition - previousOffset;
  7019. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7020. }
  7021. previousOffset = nextOffset;
  7022. }
  7023. return Vector2.Zero();
  7024. };
  7025. /**
  7026. * Returns a new Path2 starting at the coordinates (x, y).
  7027. */
  7028. Path2.StartingAt = function (x, y) {
  7029. return new Path2(x, y);
  7030. };
  7031. return Path2;
  7032. }());
  7033. BABYLON.Path2 = Path2;
  7034. var Path3D = /** @class */ (function () {
  7035. /**
  7036. * new Path3D(path, normal, raw)
  7037. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7038. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7039. * path : an array of Vector3, the curve axis of the Path3D
  7040. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7041. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7042. */
  7043. function Path3D(path, firstNormal, raw) {
  7044. if (firstNormal === void 0) { firstNormal = null; }
  7045. this.path = path;
  7046. this._curve = new Array();
  7047. this._distances = new Array();
  7048. this._tangents = new Array();
  7049. this._normals = new Array();
  7050. this._binormals = new Array();
  7051. for (var p = 0; p < path.length; p++) {
  7052. this._curve[p] = path[p].clone(); // hard copy
  7053. }
  7054. this._raw = raw || false;
  7055. this._compute(firstNormal);
  7056. }
  7057. /**
  7058. * Returns the Path3D array of successive Vector3 designing its curve.
  7059. */
  7060. Path3D.prototype.getCurve = function () {
  7061. return this._curve;
  7062. };
  7063. /**
  7064. * Returns an array populated with tangent vectors on each Path3D curve point.
  7065. */
  7066. Path3D.prototype.getTangents = function () {
  7067. return this._tangents;
  7068. };
  7069. /**
  7070. * Returns an array populated with normal vectors on each Path3D curve point.
  7071. */
  7072. Path3D.prototype.getNormals = function () {
  7073. return this._normals;
  7074. };
  7075. /**
  7076. * Returns an array populated with binormal vectors on each Path3D curve point.
  7077. */
  7078. Path3D.prototype.getBinormals = function () {
  7079. return this._binormals;
  7080. };
  7081. /**
  7082. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7083. */
  7084. Path3D.prototype.getDistances = function () {
  7085. return this._distances;
  7086. };
  7087. /**
  7088. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7089. * Returns the same object updated.
  7090. */
  7091. Path3D.prototype.update = function (path, firstNormal) {
  7092. if (firstNormal === void 0) { firstNormal = null; }
  7093. for (var p = 0; p < path.length; p++) {
  7094. this._curve[p].x = path[p].x;
  7095. this._curve[p].y = path[p].y;
  7096. this._curve[p].z = path[p].z;
  7097. }
  7098. this._compute(firstNormal);
  7099. return this;
  7100. };
  7101. // private function compute() : computes tangents, normals and binormals
  7102. Path3D.prototype._compute = function (firstNormal) {
  7103. var l = this._curve.length;
  7104. // first and last tangents
  7105. this._tangents[0] = this._getFirstNonNullVector(0);
  7106. if (!this._raw) {
  7107. this._tangents[0].normalize();
  7108. }
  7109. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7110. if (!this._raw) {
  7111. this._tangents[l - 1].normalize();
  7112. }
  7113. // normals and binormals at first point : arbitrary vector with _normalVector()
  7114. var tg0 = this._tangents[0];
  7115. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7116. this._normals[0] = pp0;
  7117. if (!this._raw) {
  7118. this._normals[0].normalize();
  7119. }
  7120. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7121. if (!this._raw) {
  7122. this._binormals[0].normalize();
  7123. }
  7124. this._distances[0] = 0.0;
  7125. // normals and binormals : next points
  7126. var prev; // previous vector (segment)
  7127. var cur; // current vector (segment)
  7128. var curTang; // current tangent
  7129. // previous normal
  7130. var prevBinor; // previous binormal
  7131. for (var i = 1; i < l; i++) {
  7132. // tangents
  7133. prev = this._getLastNonNullVector(i);
  7134. if (i < l - 1) {
  7135. cur = this._getFirstNonNullVector(i);
  7136. this._tangents[i] = prev.add(cur);
  7137. this._tangents[i].normalize();
  7138. }
  7139. this._distances[i] = this._distances[i - 1] + prev.length();
  7140. // normals and binormals
  7141. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7142. curTang = this._tangents[i];
  7143. prevBinor = this._binormals[i - 1];
  7144. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7145. if (!this._raw) {
  7146. this._normals[i].normalize();
  7147. }
  7148. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7149. if (!this._raw) {
  7150. this._binormals[i].normalize();
  7151. }
  7152. }
  7153. };
  7154. // private function getFirstNonNullVector(index)
  7155. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7156. Path3D.prototype._getFirstNonNullVector = function (index) {
  7157. var i = 1;
  7158. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7159. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7160. i++;
  7161. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7162. }
  7163. return nNVector;
  7164. };
  7165. // private function getLastNonNullVector(index)
  7166. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7167. Path3D.prototype._getLastNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7170. while (nLVector.length() === 0 && index > i + 1) {
  7171. i++;
  7172. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7173. }
  7174. return nLVector;
  7175. };
  7176. // private function normalVector(v0, vt, va) :
  7177. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7178. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7179. Path3D.prototype._normalVector = function (v0, vt, va) {
  7180. var normal0;
  7181. var tgl = vt.length();
  7182. if (tgl === 0.0) {
  7183. tgl = 1.0;
  7184. }
  7185. if (va === undefined || va === null) {
  7186. var point;
  7187. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7188. point = new Vector3(0.0, -1.0, 0.0);
  7189. }
  7190. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7191. point = new Vector3(1.0, 0.0, 0.0);
  7192. }
  7193. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7194. point = new Vector3(0.0, 0.0, 1.0);
  7195. }
  7196. else {
  7197. point = Vector3.Zero();
  7198. }
  7199. normal0 = Vector3.Cross(vt, point);
  7200. }
  7201. else {
  7202. normal0 = Vector3.Cross(vt, va);
  7203. Vector3.CrossToRef(normal0, vt, normal0);
  7204. }
  7205. normal0.normalize();
  7206. return normal0;
  7207. };
  7208. return Path3D;
  7209. }());
  7210. BABYLON.Path3D = Path3D;
  7211. var Curve3 = /** @class */ (function () {
  7212. /**
  7213. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7214. * A Curve3 is designed from a series of successive Vector3.
  7215. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7216. */
  7217. function Curve3(points) {
  7218. this._length = 0.0;
  7219. this._points = points;
  7220. this._length = this._computeLength(points);
  7221. }
  7222. /**
  7223. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7224. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7225. * @param v1 (Vector3) the control point
  7226. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7227. * @param nbPoints (integer) the wanted number of points in the curve
  7228. */
  7229. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7230. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7231. var bez = new Array();
  7232. var equation = function (t, val0, val1, val2) {
  7233. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7234. return res;
  7235. };
  7236. for (var i = 0; i <= nbPoints; i++) {
  7237. 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)));
  7238. }
  7239. return new Curve3(bez);
  7240. };
  7241. /**
  7242. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7243. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7244. * @param v1 (Vector3) the first control point
  7245. * @param v2 (Vector3) the second control point
  7246. * @param v3 (Vector3) the end point of the Cubic Bezier
  7247. * @param nbPoints (integer) the wanted number of points in the curve
  7248. */
  7249. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7250. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7251. var bez = new Array();
  7252. var equation = function (t, val0, val1, val2, val3) {
  7253. 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;
  7254. return res;
  7255. };
  7256. for (var i = 0; i <= nbPoints; i++) {
  7257. 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)));
  7258. }
  7259. return new Curve3(bez);
  7260. };
  7261. /**
  7262. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7263. * @param p1 (Vector3) the origin point of the Hermite Spline
  7264. * @param t1 (Vector3) the tangent vector at the origin point
  7265. * @param p2 (Vector3) the end point of the Hermite Spline
  7266. * @param t2 (Vector3) the tangent vector at the end point
  7267. * @param nbPoints (integer) the wanted number of points in the curve
  7268. */
  7269. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7270. var hermite = new Array();
  7271. var step = 1.0 / nbPoints;
  7272. for (var i = 0; i <= nbPoints; i++) {
  7273. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7274. }
  7275. return new Curve3(hermite);
  7276. };
  7277. /**
  7278. * Returns a Curve3 object along a CatmullRom Spline curve :
  7279. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7280. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7281. */
  7282. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7283. var totalPoints = new Array();
  7284. totalPoints.push(points[0].clone());
  7285. Array.prototype.push.apply(totalPoints, points);
  7286. totalPoints.push(points[points.length - 1].clone());
  7287. var catmullRom = new Array();
  7288. var step = 1.0 / nbPoints;
  7289. var amount = 0.0;
  7290. for (var i = 0; i < totalPoints.length - 3; i++) {
  7291. amount = 0;
  7292. for (var c = 0; c < nbPoints; c++) {
  7293. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7294. amount += step;
  7295. }
  7296. }
  7297. i--;
  7298. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7299. return new Curve3(catmullRom);
  7300. };
  7301. /**
  7302. * Returns the Curve3 stored array of successive Vector3
  7303. */
  7304. Curve3.prototype.getPoints = function () {
  7305. return this._points;
  7306. };
  7307. /**
  7308. * Returns the computed length (float) of the curve.
  7309. */
  7310. Curve3.prototype.length = function () {
  7311. return this._length;
  7312. };
  7313. /**
  7314. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7315. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7316. * curveA and curveB keep unchanged.
  7317. */
  7318. Curve3.prototype.continue = function (curve) {
  7319. var lastPoint = this._points[this._points.length - 1];
  7320. var continuedPoints = this._points.slice();
  7321. var curvePoints = curve.getPoints();
  7322. for (var i = 1; i < curvePoints.length; i++) {
  7323. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7324. }
  7325. var continuedCurve = new Curve3(continuedPoints);
  7326. return continuedCurve;
  7327. };
  7328. Curve3.prototype._computeLength = function (path) {
  7329. var l = 0;
  7330. for (var i = 1; i < path.length; i++) {
  7331. l += (path[i].subtract(path[i - 1])).length();
  7332. }
  7333. return l;
  7334. };
  7335. return Curve3;
  7336. }());
  7337. BABYLON.Curve3 = Curve3;
  7338. // Vertex formats
  7339. var PositionNormalVertex = /** @class */ (function () {
  7340. function PositionNormalVertex(position, normal) {
  7341. if (position === void 0) { position = Vector3.Zero(); }
  7342. if (normal === void 0) { normal = Vector3.Up(); }
  7343. this.position = position;
  7344. this.normal = normal;
  7345. }
  7346. PositionNormalVertex.prototype.clone = function () {
  7347. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7348. };
  7349. return PositionNormalVertex;
  7350. }());
  7351. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7352. var PositionNormalTextureVertex = /** @class */ (function () {
  7353. function PositionNormalTextureVertex(position, normal, uv) {
  7354. if (position === void 0) { position = Vector3.Zero(); }
  7355. if (normal === void 0) { normal = Vector3.Up(); }
  7356. if (uv === void 0) { uv = Vector2.Zero(); }
  7357. this.position = position;
  7358. this.normal = normal;
  7359. this.uv = uv;
  7360. }
  7361. PositionNormalTextureVertex.prototype.clone = function () {
  7362. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7363. };
  7364. return PositionNormalTextureVertex;
  7365. }());
  7366. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7367. // Temporary pre-allocated objects for engine internal use
  7368. // usage in any internal function :
  7369. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7370. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7371. var Tmp = /** @class */ (function () {
  7372. function Tmp() {
  7373. }
  7374. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7375. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7376. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7377. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7378. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7379. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7380. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7381. Matrix.Zero(), Matrix.Zero(),
  7382. Matrix.Zero(), Matrix.Zero(),
  7383. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7384. return Tmp;
  7385. }());
  7386. BABYLON.Tmp = Tmp;
  7387. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7388. var MathTmp = /** @class */ (function () {
  7389. function MathTmp() {
  7390. }
  7391. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7392. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7393. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7394. return MathTmp;
  7395. }());
  7396. })(BABYLON || (BABYLON = {}));
  7397. //# sourceMappingURL=babylon.math.js.map
  7398. var BABYLON;
  7399. (function (BABYLON) {
  7400. var Scalar = /** @class */ (function () {
  7401. function Scalar() {
  7402. }
  7403. /**
  7404. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7405. */
  7406. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7407. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7408. var num = a - b;
  7409. return -epsilon <= num && num <= epsilon;
  7410. };
  7411. /**
  7412. * Returns a string : the upper case translation of the number i to hexadecimal.
  7413. */
  7414. Scalar.ToHex = function (i) {
  7415. var str = i.toString(16);
  7416. if (i <= 15) {
  7417. return ("0" + str).toUpperCase();
  7418. }
  7419. return str.toUpperCase();
  7420. };
  7421. /**
  7422. * Returns -1 if value is negative and +1 is value is positive.
  7423. * Returns the value itself if it's equal to zero.
  7424. */
  7425. Scalar.Sign = function (value) {
  7426. value = +value; // convert to a number
  7427. if (value === 0 || isNaN(value))
  7428. return value;
  7429. return value > 0 ? 1 : -1;
  7430. };
  7431. /**
  7432. * Returns the value itself if it's between min and max.
  7433. * Returns min if the value is lower than min.
  7434. * Returns max if the value is greater than max.
  7435. */
  7436. Scalar.Clamp = function (value, min, max) {
  7437. if (min === void 0) { min = 0; }
  7438. if (max === void 0) { max = 1; }
  7439. return Math.min(max, Math.max(min, value));
  7440. };
  7441. /**
  7442. * Returns the log2 of value.
  7443. */
  7444. Scalar.Log2 = function (value) {
  7445. return Math.log(value) * Math.LOG2E;
  7446. };
  7447. /**
  7448. * Loops the value, so that it is never larger than length and never smaller than 0.
  7449. *
  7450. * This is similar to the modulo operator but it works with floating point numbers.
  7451. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7452. * With t = 5 and length = 2.5, the result would be 0.0.
  7453. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7454. */
  7455. Scalar.Repeat = function (value, length) {
  7456. return value - Math.floor(value / length) * length;
  7457. };
  7458. /**
  7459. * Normalize the value between 0.0 and 1.0 using min and max values
  7460. */
  7461. Scalar.Normalize = function (value, min, max) {
  7462. return (value - min) / (max - min);
  7463. };
  7464. /**
  7465. * Denormalize the value from 0.0 and 1.0 using min and max values
  7466. */
  7467. Scalar.Denormalize = function (normalized, min, max) {
  7468. return (normalized * (max - min) + min);
  7469. };
  7470. /**
  7471. * Calculates the shortest difference between two given angles given in degrees.
  7472. */
  7473. Scalar.DeltaAngle = function (current, target) {
  7474. var num = Scalar.Repeat(target - current, 360.0);
  7475. if (num > 180.0) {
  7476. num -= 360.0;
  7477. }
  7478. return num;
  7479. };
  7480. /**
  7481. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7482. *
  7483. * The returned value will move back and forth between 0 and length
  7484. */
  7485. Scalar.PingPong = function (tx, length) {
  7486. var t = Scalar.Repeat(tx, length * 2.0);
  7487. return length - Math.abs(t - length);
  7488. };
  7489. /**
  7490. * Interpolates between min and max with smoothing at the limits.
  7491. *
  7492. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7493. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7494. */
  7495. Scalar.SmoothStep = function (from, to, tx) {
  7496. var t = Scalar.Clamp(tx);
  7497. t = -2.0 * t * t * t + 3.0 * t * t;
  7498. return to * t + from * (1.0 - t);
  7499. };
  7500. /**
  7501. * Moves a value current towards target.
  7502. *
  7503. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7504. * Negative values of maxDelta pushes the value away from target.
  7505. */
  7506. Scalar.MoveTowards = function (current, target, maxDelta) {
  7507. var result = 0;
  7508. if (Math.abs(target - current) <= maxDelta) {
  7509. result = target;
  7510. }
  7511. else {
  7512. result = current + Scalar.Sign(target - current) * maxDelta;
  7513. }
  7514. return result;
  7515. };
  7516. /**
  7517. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7518. *
  7519. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7520. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7521. */
  7522. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7523. var num = Scalar.DeltaAngle(current, target);
  7524. var result = 0;
  7525. if (-maxDelta < num && num < maxDelta) {
  7526. result = target;
  7527. }
  7528. else {
  7529. target = current + num;
  7530. result = Scalar.MoveTowards(current, target, maxDelta);
  7531. }
  7532. return result;
  7533. };
  7534. /**
  7535. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7536. */
  7537. Scalar.Lerp = function (start, end, amount) {
  7538. return start + ((end - start) * amount);
  7539. };
  7540. /**
  7541. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7542. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7543. */
  7544. Scalar.LerpAngle = function (start, end, amount) {
  7545. var num = Scalar.Repeat(end - start, 360.0);
  7546. if (num > 180.0) {
  7547. num -= 360.0;
  7548. }
  7549. return start + num * Scalar.Clamp(amount);
  7550. };
  7551. /**
  7552. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7553. */
  7554. Scalar.InverseLerp = function (a, b, value) {
  7555. var result = 0;
  7556. if (a != b) {
  7557. result = Scalar.Clamp((value - a) / (b - a));
  7558. }
  7559. else {
  7560. result = 0.0;
  7561. }
  7562. return result;
  7563. };
  7564. /**
  7565. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7566. */
  7567. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7568. var squared = amount * amount;
  7569. var cubed = amount * squared;
  7570. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7571. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7572. var part3 = (cubed - (2.0 * squared)) + amount;
  7573. var part4 = cubed - squared;
  7574. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7575. };
  7576. /**
  7577. * Returns a random float number between and min and max values
  7578. */
  7579. Scalar.RandomRange = function (min, max) {
  7580. if (min === max)
  7581. return min;
  7582. return ((Math.random() * (max - min)) + min);
  7583. };
  7584. /**
  7585. * This function returns percentage of a number in a given range.
  7586. *
  7587. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7588. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7589. */
  7590. Scalar.RangeToPercent = function (number, min, max) {
  7591. return ((number - min) / (max - min));
  7592. };
  7593. /**
  7594. * This function returns number that corresponds to the percentage in a given range.
  7595. *
  7596. * PercentToRange(0.34,0,100) will return 34.
  7597. */
  7598. Scalar.PercentToRange = function (percent, min, max) {
  7599. return ((max - min) * percent + min);
  7600. };
  7601. /**
  7602. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7603. * @param angle The angle to normalize in radian.
  7604. * @return The converted angle.
  7605. */
  7606. Scalar.NormalizeRadians = function (angle) {
  7607. // More precise but slower version kept for reference.
  7608. // angle = angle % Tools.TwoPi;
  7609. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7610. //if (angle > Math.PI) {
  7611. // angle -= Tools.TwoPi;
  7612. //}
  7613. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7614. return angle;
  7615. };
  7616. /**
  7617. * Two pi constants convenient for computation.
  7618. */
  7619. Scalar.TwoPi = Math.PI * 2;
  7620. return Scalar;
  7621. }());
  7622. BABYLON.Scalar = Scalar;
  7623. })(BABYLON || (BABYLON = {}));
  7624. //# sourceMappingURL=babylon.math.scalar.js.map
  7625. //# sourceMappingURL=babylon.mixins.js.map
  7626. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7627. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7628. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7629. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7630. //# sourceMappingURL=babylon.webgl2.js.map
  7631. var BABYLON;
  7632. (function (BABYLON) {
  7633. var __decoratorInitialStore = {};
  7634. var __mergedStore = {};
  7635. var _copySource = function (creationFunction, source, instanciate) {
  7636. var destination = creationFunction();
  7637. // Tags
  7638. if (BABYLON.Tags) {
  7639. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7640. }
  7641. var classStore = getMergedStore(destination);
  7642. // Properties
  7643. for (var property in classStore) {
  7644. var propertyDescriptor = classStore[property];
  7645. var sourceProperty = source[property];
  7646. var propertyType = propertyDescriptor.type;
  7647. if (sourceProperty !== undefined && sourceProperty !== null) {
  7648. switch (propertyType) {
  7649. case 0: // Value
  7650. case 6: // Mesh reference
  7651. case 11: // Camera reference
  7652. destination[property] = sourceProperty;
  7653. break;
  7654. case 1: // Texture
  7655. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7656. break;
  7657. case 2: // Color3
  7658. case 3: // FresnelParameters
  7659. case 4: // Vector2
  7660. case 5: // Vector3
  7661. case 7: // Color Curves
  7662. case 10: // Quaternion
  7663. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7664. break;
  7665. }
  7666. }
  7667. }
  7668. return destination;
  7669. };
  7670. function getDirectStore(target) {
  7671. var classKey = target.getClassName();
  7672. if (!__decoratorInitialStore[classKey]) {
  7673. __decoratorInitialStore[classKey] = {};
  7674. }
  7675. return __decoratorInitialStore[classKey];
  7676. }
  7677. /**
  7678. * Return the list of properties flagged as serializable
  7679. * @param target: host object
  7680. */
  7681. function getMergedStore(target) {
  7682. var classKey = target.getClassName();
  7683. if (__mergedStore[classKey]) {
  7684. return __mergedStore[classKey];
  7685. }
  7686. __mergedStore[classKey] = {};
  7687. var store = __mergedStore[classKey];
  7688. var currentTarget = target;
  7689. var currentKey = classKey;
  7690. while (currentKey) {
  7691. var initialStore = __decoratorInitialStore[currentKey];
  7692. for (var property in initialStore) {
  7693. store[property] = initialStore[property];
  7694. }
  7695. var parent_1 = void 0;
  7696. var done = false;
  7697. do {
  7698. parent_1 = Object.getPrototypeOf(currentTarget);
  7699. if (!parent_1.getClassName) {
  7700. done = true;
  7701. break;
  7702. }
  7703. if (parent_1.getClassName() !== currentKey) {
  7704. break;
  7705. }
  7706. currentTarget = parent_1;
  7707. } while (parent_1);
  7708. if (done) {
  7709. break;
  7710. }
  7711. currentKey = parent_1.getClassName();
  7712. currentTarget = parent_1;
  7713. }
  7714. return store;
  7715. }
  7716. function generateSerializableMember(type, sourceName) {
  7717. return function (target, propertyKey) {
  7718. var classStore = getDirectStore(target);
  7719. if (!classStore[propertyKey]) {
  7720. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7721. }
  7722. };
  7723. }
  7724. function generateExpandMember(setCallback, targetKey) {
  7725. if (targetKey === void 0) { targetKey = null; }
  7726. return function (target, propertyKey) {
  7727. var key = targetKey || ("_" + propertyKey);
  7728. Object.defineProperty(target, propertyKey, {
  7729. get: function () {
  7730. return this[key];
  7731. },
  7732. set: function (value) {
  7733. if (this[key] === value) {
  7734. return;
  7735. }
  7736. this[key] = value;
  7737. target[setCallback].apply(this);
  7738. },
  7739. enumerable: true,
  7740. configurable: true
  7741. });
  7742. };
  7743. }
  7744. function expandToProperty(callback, targetKey) {
  7745. if (targetKey === void 0) { targetKey = null; }
  7746. return generateExpandMember(callback, targetKey);
  7747. }
  7748. BABYLON.expandToProperty = expandToProperty;
  7749. function serialize(sourceName) {
  7750. return generateSerializableMember(0, sourceName); // value member
  7751. }
  7752. BABYLON.serialize = serialize;
  7753. function serializeAsTexture(sourceName) {
  7754. return generateSerializableMember(1, sourceName); // texture member
  7755. }
  7756. BABYLON.serializeAsTexture = serializeAsTexture;
  7757. function serializeAsColor3(sourceName) {
  7758. return generateSerializableMember(2, sourceName); // color3 member
  7759. }
  7760. BABYLON.serializeAsColor3 = serializeAsColor3;
  7761. function serializeAsFresnelParameters(sourceName) {
  7762. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7763. }
  7764. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7765. function serializeAsVector2(sourceName) {
  7766. return generateSerializableMember(4, sourceName); // vector2 member
  7767. }
  7768. BABYLON.serializeAsVector2 = serializeAsVector2;
  7769. function serializeAsVector3(sourceName) {
  7770. return generateSerializableMember(5, sourceName); // vector3 member
  7771. }
  7772. BABYLON.serializeAsVector3 = serializeAsVector3;
  7773. function serializeAsMeshReference(sourceName) {
  7774. return generateSerializableMember(6, sourceName); // mesh reference member
  7775. }
  7776. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7777. function serializeAsColorCurves(sourceName) {
  7778. return generateSerializableMember(7, sourceName); // color curves
  7779. }
  7780. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7781. function serializeAsColor4(sourceName) {
  7782. return generateSerializableMember(8, sourceName); // color 4
  7783. }
  7784. BABYLON.serializeAsColor4 = serializeAsColor4;
  7785. function serializeAsImageProcessingConfiguration(sourceName) {
  7786. return generateSerializableMember(9, sourceName); // image processing
  7787. }
  7788. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7789. function serializeAsQuaternion(sourceName) {
  7790. return generateSerializableMember(10, sourceName); // quaternion member
  7791. }
  7792. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7793. /**
  7794. * Decorator used to define property that can be serialized as reference to a camera
  7795. * @param sourceName defines the name of the property to decorate
  7796. */
  7797. function serializeAsCameraReference(sourceName) {
  7798. return generateSerializableMember(11, sourceName); // camera reference member
  7799. }
  7800. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7801. var SerializationHelper = /** @class */ (function () {
  7802. function SerializationHelper() {
  7803. }
  7804. SerializationHelper.Serialize = function (entity, serializationObject) {
  7805. if (!serializationObject) {
  7806. serializationObject = {};
  7807. }
  7808. // Tags
  7809. if (BABYLON.Tags) {
  7810. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7811. }
  7812. var serializedProperties = getMergedStore(entity);
  7813. // Properties
  7814. for (var property in serializedProperties) {
  7815. var propertyDescriptor = serializedProperties[property];
  7816. var targetPropertyName = propertyDescriptor.sourceName || property;
  7817. var propertyType = propertyDescriptor.type;
  7818. var sourceProperty = entity[property];
  7819. if (sourceProperty !== undefined && sourceProperty !== null) {
  7820. switch (propertyType) {
  7821. case 0: // Value
  7822. serializationObject[targetPropertyName] = sourceProperty;
  7823. break;
  7824. case 1: // Texture
  7825. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7826. break;
  7827. case 2: // Color3
  7828. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7829. break;
  7830. case 3: // FresnelParameters
  7831. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7832. break;
  7833. case 4: // Vector2
  7834. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7835. break;
  7836. case 5: // Vector3
  7837. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7838. break;
  7839. case 6: // Mesh reference
  7840. serializationObject[targetPropertyName] = sourceProperty.id;
  7841. break;
  7842. case 7: // Color Curves
  7843. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7844. break;
  7845. case 8: // Color 4
  7846. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7847. break;
  7848. case 9: // Image Processing
  7849. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7850. break;
  7851. case 10: // Quaternion
  7852. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7853. break;
  7854. case 11: // Camera reference
  7855. serializationObject[targetPropertyName] = sourceProperty.id;
  7856. break;
  7857. }
  7858. }
  7859. }
  7860. return serializationObject;
  7861. };
  7862. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7863. if (rootUrl === void 0) { rootUrl = null; }
  7864. var destination = creationFunction();
  7865. if (!rootUrl) {
  7866. rootUrl = "";
  7867. }
  7868. // Tags
  7869. if (BABYLON.Tags) {
  7870. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7871. }
  7872. var classStore = getMergedStore(destination);
  7873. // Properties
  7874. for (var property in classStore) {
  7875. var propertyDescriptor = classStore[property];
  7876. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7877. var propertyType = propertyDescriptor.type;
  7878. if (sourceProperty !== undefined && sourceProperty !== null) {
  7879. var dest = destination;
  7880. switch (propertyType) {
  7881. case 0: // Value
  7882. dest[property] = sourceProperty;
  7883. break;
  7884. case 1: // Texture
  7885. if (scene) {
  7886. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7887. }
  7888. break;
  7889. case 2: // Color3
  7890. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7891. break;
  7892. case 3: // FresnelParameters
  7893. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7894. break;
  7895. case 4: // Vector2
  7896. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7897. break;
  7898. case 5: // Vector3
  7899. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7900. break;
  7901. case 6: // Mesh reference
  7902. if (scene) {
  7903. dest[property] = scene.getLastMeshByID(sourceProperty);
  7904. }
  7905. break;
  7906. case 7: // Color Curves
  7907. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7908. break;
  7909. case 8: // Color 4
  7910. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7911. break;
  7912. case 9: // Image Processing
  7913. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7914. break;
  7915. case 10: // Quaternion
  7916. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7917. break;
  7918. case 11: // Camera reference
  7919. if (scene) {
  7920. dest[property] = scene.getCameraByID(sourceProperty);
  7921. }
  7922. break;
  7923. }
  7924. }
  7925. }
  7926. return destination;
  7927. };
  7928. SerializationHelper.Clone = function (creationFunction, source) {
  7929. return _copySource(creationFunction, source, false);
  7930. };
  7931. SerializationHelper.Instanciate = function (creationFunction, source) {
  7932. return _copySource(creationFunction, source, true);
  7933. };
  7934. return SerializationHelper;
  7935. }());
  7936. BABYLON.SerializationHelper = SerializationHelper;
  7937. })(BABYLON || (BABYLON = {}));
  7938. //# sourceMappingURL=babylon.decorators.js.map
  7939. var BABYLON;
  7940. (function (BABYLON) {
  7941. /**
  7942. * Wrapper class for promise with external resolve and reject.
  7943. */
  7944. var Deferred = /** @class */ (function () {
  7945. /**
  7946. * Constructor for this deferred object.
  7947. */
  7948. function Deferred() {
  7949. var _this = this;
  7950. this.promise = new Promise(function (resolve, reject) {
  7951. _this._resolve = resolve;
  7952. _this._reject = reject;
  7953. });
  7954. }
  7955. Object.defineProperty(Deferred.prototype, "resolve", {
  7956. /**
  7957. * The resolve method of the promise associated with this deferred object.
  7958. */
  7959. get: function () {
  7960. return this._resolve;
  7961. },
  7962. enumerable: true,
  7963. configurable: true
  7964. });
  7965. Object.defineProperty(Deferred.prototype, "reject", {
  7966. /**
  7967. * The reject method of the promise associated with this deferred object.
  7968. */
  7969. get: function () {
  7970. return this._reject;
  7971. },
  7972. enumerable: true,
  7973. configurable: true
  7974. });
  7975. return Deferred;
  7976. }());
  7977. BABYLON.Deferred = Deferred;
  7978. })(BABYLON || (BABYLON = {}));
  7979. //# sourceMappingURL=babylon.deferred.js.map
  7980. var BABYLON;
  7981. (function (BABYLON) {
  7982. /**
  7983. * A class serves as a medium between the observable and its observers
  7984. */
  7985. var EventState = /** @class */ (function () {
  7986. /**
  7987. * Create a new EventState
  7988. * @param mask defines the mask associated with this state
  7989. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7990. * @param target defines the original target of the state
  7991. * @param currentTarget defines the current target of the state
  7992. */
  7993. function EventState(mask, skipNextObservers, target, currentTarget) {
  7994. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7995. this.initalize(mask, skipNextObservers, target, currentTarget);
  7996. }
  7997. /**
  7998. * Initialize the current event state
  7999. * @param mask defines the mask associated with this state
  8000. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8001. * @param target defines the original target of the state
  8002. * @param currentTarget defines the current target of the state
  8003. * @returns the current event state
  8004. */
  8005. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8006. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8007. this.mask = mask;
  8008. this.skipNextObservers = skipNextObservers;
  8009. this.target = target;
  8010. this.currentTarget = currentTarget;
  8011. return this;
  8012. };
  8013. return EventState;
  8014. }());
  8015. BABYLON.EventState = EventState;
  8016. /**
  8017. * Represent an Observer registered to a given Observable object.
  8018. */
  8019. var Observer = /** @class */ (function () {
  8020. /**
  8021. * Creates a new observer
  8022. * @param callback defines the callback to call when the observer is notified
  8023. * @param mask defines the mask of the observer (used to filter notifications)
  8024. * @param scope defines the current scope used to restore the JS context
  8025. */
  8026. function Observer(
  8027. /**
  8028. * Defines the callback to call when the observer is notified
  8029. */
  8030. callback,
  8031. /**
  8032. * Defines the mask of the observer (used to filter notifications)
  8033. */
  8034. mask,
  8035. /**
  8036. * Defines the current scope used to restore the JS context
  8037. */
  8038. scope) {
  8039. if (scope === void 0) { scope = null; }
  8040. this.callback = callback;
  8041. this.mask = mask;
  8042. this.scope = scope;
  8043. /** @hidden */
  8044. this._willBeUnregistered = false;
  8045. /**
  8046. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8047. */
  8048. this.unregisterOnNextCall = false;
  8049. }
  8050. return Observer;
  8051. }());
  8052. BABYLON.Observer = Observer;
  8053. /**
  8054. * Represent a list of observers registered to multiple Observables object.
  8055. */
  8056. var MultiObserver = /** @class */ (function () {
  8057. function MultiObserver() {
  8058. }
  8059. /**
  8060. * Release associated resources
  8061. */
  8062. MultiObserver.prototype.dispose = function () {
  8063. if (this._observers && this._observables) {
  8064. for (var index = 0; index < this._observers.length; index++) {
  8065. this._observables[index].remove(this._observers[index]);
  8066. }
  8067. }
  8068. this._observers = null;
  8069. this._observables = null;
  8070. };
  8071. /**
  8072. * Raise a callback when one of the observable will notify
  8073. * @param observables defines a list of observables to watch
  8074. * @param callback defines the callback to call on notification
  8075. * @param mask defines the mask used to filter notifications
  8076. * @param scope defines the current scope used to restore the JS context
  8077. * @returns the new MultiObserver
  8078. */
  8079. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8080. if (mask === void 0) { mask = -1; }
  8081. if (scope === void 0) { scope = null; }
  8082. var result = new MultiObserver();
  8083. result._observers = new Array();
  8084. result._observables = observables;
  8085. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8086. var observable = observables_1[_i];
  8087. var observer = observable.add(callback, mask, false, scope);
  8088. if (observer) {
  8089. result._observers.push(observer);
  8090. }
  8091. }
  8092. return result;
  8093. };
  8094. return MultiObserver;
  8095. }());
  8096. BABYLON.MultiObserver = MultiObserver;
  8097. /**
  8098. * The Observable class is a simple implementation of the Observable pattern.
  8099. *
  8100. * 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.
  8101. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8102. * 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).
  8103. * 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.
  8104. */
  8105. var Observable = /** @class */ (function () {
  8106. /**
  8107. * Creates a new observable
  8108. * @param onObserverAdded defines a callback to call when a new observer is added
  8109. */
  8110. function Observable(onObserverAdded) {
  8111. this._observers = new Array();
  8112. this._eventState = new EventState(0);
  8113. if (onObserverAdded) {
  8114. this._onObserverAdded = onObserverAdded;
  8115. }
  8116. }
  8117. /**
  8118. * Create a new Observer with the specified callback
  8119. * @param callback the callback that will be executed for that Observer
  8120. * @param mask the mask used to filter observers
  8121. * @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.
  8122. * @param scope optional scope for the callback to be called from
  8123. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8124. * @returns the new observer created for the callback
  8125. */
  8126. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8127. if (mask === void 0) { mask = -1; }
  8128. if (insertFirst === void 0) { insertFirst = false; }
  8129. if (scope === void 0) { scope = null; }
  8130. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8131. if (!callback) {
  8132. return null;
  8133. }
  8134. var observer = new Observer(callback, mask, scope);
  8135. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8136. if (insertFirst) {
  8137. this._observers.unshift(observer);
  8138. }
  8139. else {
  8140. this._observers.push(observer);
  8141. }
  8142. if (this._onObserverAdded) {
  8143. this._onObserverAdded(observer);
  8144. }
  8145. return observer;
  8146. };
  8147. /**
  8148. * Remove an Observer from the Observable object
  8149. * @param observer the instance of the Observer to remove
  8150. * @returns false if it doesn't belong to this Observable
  8151. */
  8152. Observable.prototype.remove = function (observer) {
  8153. if (!observer) {
  8154. return false;
  8155. }
  8156. var index = this._observers.indexOf(observer);
  8157. if (index !== -1) {
  8158. this._observers.splice(index, 1);
  8159. return true;
  8160. }
  8161. return false;
  8162. };
  8163. /**
  8164. * Remove a callback from the Observable object
  8165. * @param callback the callback to remove
  8166. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8167. * @returns false if it doesn't belong to this Observable
  8168. */
  8169. Observable.prototype.removeCallback = function (callback, scope) {
  8170. for (var index = 0; index < this._observers.length; index++) {
  8171. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8172. this._observers.splice(index, 1);
  8173. return true;
  8174. }
  8175. }
  8176. return false;
  8177. };
  8178. Observable.prototype._deferUnregister = function (observer) {
  8179. var _this = this;
  8180. observer.unregisterOnNextCall = false;
  8181. observer._willBeUnregistered = true;
  8182. BABYLON.Tools.SetImmediate(function () {
  8183. _this.remove(observer);
  8184. });
  8185. };
  8186. /**
  8187. * Notify all Observers by calling their respective callback with the given data
  8188. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8189. * @param eventData defines the data to send to all observers
  8190. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8191. * @param target defines the original target of the state
  8192. * @param currentTarget defines the current target of the state
  8193. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8194. */
  8195. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8196. if (mask === void 0) { mask = -1; }
  8197. if (!this._observers.length) {
  8198. return true;
  8199. }
  8200. var state = this._eventState;
  8201. state.mask = mask;
  8202. state.target = target;
  8203. state.currentTarget = currentTarget;
  8204. state.skipNextObservers = false;
  8205. state.lastReturnValue = eventData;
  8206. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8207. var obs = _a[_i];
  8208. if (obs._willBeUnregistered) {
  8209. continue;
  8210. }
  8211. if (obs.mask & mask) {
  8212. if (obs.scope) {
  8213. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8214. }
  8215. else {
  8216. state.lastReturnValue = obs.callback(eventData, state);
  8217. }
  8218. if (obs.unregisterOnNextCall) {
  8219. this._deferUnregister(obs);
  8220. }
  8221. }
  8222. if (state.skipNextObservers) {
  8223. return false;
  8224. }
  8225. }
  8226. return true;
  8227. };
  8228. /**
  8229. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8230. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8231. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8232. * and it is crucial that all callbacks will be executed.
  8233. * The order of the callbacks is kept, callbacks are not executed parallel.
  8234. *
  8235. * @param eventData The data to be sent to each callback
  8236. * @param mask is used to filter observers defaults to -1
  8237. * @param target defines the callback target (see EventState)
  8238. * @param currentTarget defines he current object in the bubbling phase
  8239. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8240. */
  8241. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8242. var _this = this;
  8243. if (mask === void 0) { mask = -1; }
  8244. // create an empty promise
  8245. var p = Promise.resolve(eventData);
  8246. // no observers? return this promise.
  8247. if (!this._observers.length) {
  8248. return p;
  8249. }
  8250. var state = this._eventState;
  8251. state.mask = mask;
  8252. state.target = target;
  8253. state.currentTarget = currentTarget;
  8254. state.skipNextObservers = false;
  8255. // execute one callback after another (not using Promise.all, the order is important)
  8256. this._observers.forEach(function (obs) {
  8257. if (state.skipNextObservers) {
  8258. return;
  8259. }
  8260. if (obs._willBeUnregistered) {
  8261. return;
  8262. }
  8263. if (obs.mask & mask) {
  8264. if (obs.scope) {
  8265. p = p.then(function (lastReturnedValue) {
  8266. state.lastReturnValue = lastReturnedValue;
  8267. return obs.callback.apply(obs.scope, [eventData, state]);
  8268. });
  8269. }
  8270. else {
  8271. p = p.then(function (lastReturnedValue) {
  8272. state.lastReturnValue = lastReturnedValue;
  8273. return obs.callback(eventData, state);
  8274. });
  8275. }
  8276. if (obs.unregisterOnNextCall) {
  8277. _this._deferUnregister(obs);
  8278. }
  8279. }
  8280. });
  8281. // return the eventData
  8282. return p.then(function () { return eventData; });
  8283. };
  8284. /**
  8285. * Notify a specific observer
  8286. * @param observer defines the observer to notify
  8287. * @param eventData defines the data to be sent to each callback
  8288. * @param mask is used to filter observers defaults to -1
  8289. */
  8290. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8291. if (mask === void 0) { mask = -1; }
  8292. var state = this._eventState;
  8293. state.mask = mask;
  8294. state.skipNextObservers = false;
  8295. observer.callback(eventData, state);
  8296. };
  8297. /**
  8298. * Gets a boolean indicating if the observable has at least one observer
  8299. * @returns true is the Observable has at least one Observer registered
  8300. */
  8301. Observable.prototype.hasObservers = function () {
  8302. return this._observers.length > 0;
  8303. };
  8304. /**
  8305. * Clear the list of observers
  8306. */
  8307. Observable.prototype.clear = function () {
  8308. this._observers = new Array();
  8309. this._onObserverAdded = null;
  8310. };
  8311. /**
  8312. * Clone the current observable
  8313. * @returns a new observable
  8314. */
  8315. Observable.prototype.clone = function () {
  8316. var result = new Observable();
  8317. result._observers = this._observers.slice(0);
  8318. return result;
  8319. };
  8320. /**
  8321. * Does this observable handles observer registered with a given mask
  8322. * @param mask defines the mask to be tested
  8323. * @return whether or not one observer registered with the given mask is handeled
  8324. **/
  8325. Observable.prototype.hasSpecificMask = function (mask) {
  8326. if (mask === void 0) { mask = -1; }
  8327. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8328. var obs = _a[_i];
  8329. if (obs.mask & mask || obs.mask === mask) {
  8330. return true;
  8331. }
  8332. }
  8333. return false;
  8334. };
  8335. return Observable;
  8336. }());
  8337. BABYLON.Observable = Observable;
  8338. })(BABYLON || (BABYLON = {}));
  8339. //# sourceMappingURL=babylon.observable.js.map
  8340. var BABYLON;
  8341. (function (BABYLON) {
  8342. var SmartArray = /** @class */ (function () {
  8343. function SmartArray(capacity) {
  8344. this.length = 0;
  8345. this.data = new Array(capacity);
  8346. this._id = SmartArray._GlobalId++;
  8347. }
  8348. SmartArray.prototype.push = function (value) {
  8349. this.data[this.length++] = value;
  8350. if (this.length > this.data.length) {
  8351. this.data.length *= 2;
  8352. }
  8353. };
  8354. SmartArray.prototype.forEach = function (func) {
  8355. for (var index = 0; index < this.length; index++) {
  8356. func(this.data[index]);
  8357. }
  8358. };
  8359. SmartArray.prototype.sort = function (compareFn) {
  8360. this.data.sort(compareFn);
  8361. };
  8362. SmartArray.prototype.reset = function () {
  8363. this.length = 0;
  8364. };
  8365. SmartArray.prototype.dispose = function () {
  8366. this.reset();
  8367. if (this.data) {
  8368. this.data.length = 0;
  8369. this.data = [];
  8370. }
  8371. };
  8372. SmartArray.prototype.concat = function (array) {
  8373. if (array.length === 0) {
  8374. return;
  8375. }
  8376. if (this.length + array.length > this.data.length) {
  8377. this.data.length = (this.length + array.length) * 2;
  8378. }
  8379. for (var index = 0; index < array.length; index++) {
  8380. this.data[this.length++] = (array.data || array)[index];
  8381. }
  8382. };
  8383. SmartArray.prototype.indexOf = function (value) {
  8384. var position = this.data.indexOf(value);
  8385. if (position >= this.length) {
  8386. return -1;
  8387. }
  8388. return position;
  8389. };
  8390. SmartArray.prototype.contains = function (value) {
  8391. return this.data.indexOf(value) !== -1;
  8392. };
  8393. // Statics
  8394. SmartArray._GlobalId = 0;
  8395. return SmartArray;
  8396. }());
  8397. BABYLON.SmartArray = SmartArray;
  8398. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8399. __extends(SmartArrayNoDuplicate, _super);
  8400. function SmartArrayNoDuplicate() {
  8401. var _this = _super !== null && _super.apply(this, arguments) || this;
  8402. _this._duplicateId = 0;
  8403. return _this;
  8404. }
  8405. SmartArrayNoDuplicate.prototype.push = function (value) {
  8406. _super.prototype.push.call(this, value);
  8407. if (!value.__smartArrayFlags) {
  8408. value.__smartArrayFlags = {};
  8409. }
  8410. value.__smartArrayFlags[this._id] = this._duplicateId;
  8411. };
  8412. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8413. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8414. return false;
  8415. }
  8416. this.push(value);
  8417. return true;
  8418. };
  8419. SmartArrayNoDuplicate.prototype.reset = function () {
  8420. _super.prototype.reset.call(this);
  8421. this._duplicateId++;
  8422. };
  8423. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8424. if (array.length === 0) {
  8425. return;
  8426. }
  8427. if (this.length + array.length > this.data.length) {
  8428. this.data.length = (this.length + array.length) * 2;
  8429. }
  8430. for (var index = 0; index < array.length; index++) {
  8431. var item = (array.data || array)[index];
  8432. this.pushNoDuplicate(item);
  8433. }
  8434. };
  8435. return SmartArrayNoDuplicate;
  8436. }(SmartArray));
  8437. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8438. })(BABYLON || (BABYLON = {}));
  8439. //# sourceMappingURL=babylon.smartArray.js.map
  8440. var BABYLON;
  8441. (function (BABYLON) {
  8442. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8443. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8444. var LoadFileError = /** @class */ (function (_super) {
  8445. __extends(LoadFileError, _super);
  8446. function LoadFileError(message, request) {
  8447. var _this = _super.call(this, message) || this;
  8448. _this.request = request;
  8449. _this.name = "LoadFileError";
  8450. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8451. return _this;
  8452. }
  8453. // Polyfill for Object.setPrototypeOf if necessary.
  8454. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8455. return LoadFileError;
  8456. }(Error));
  8457. BABYLON.LoadFileError = LoadFileError;
  8458. var RetryStrategy = /** @class */ (function () {
  8459. function RetryStrategy() {
  8460. }
  8461. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8462. if (maxRetries === void 0) { maxRetries = 3; }
  8463. if (baseInterval === void 0) { baseInterval = 500; }
  8464. return function (url, request, retryIndex) {
  8465. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8466. return -1;
  8467. }
  8468. return Math.pow(2, retryIndex) * baseInterval;
  8469. };
  8470. };
  8471. return RetryStrategy;
  8472. }());
  8473. BABYLON.RetryStrategy = RetryStrategy;
  8474. // Screenshots
  8475. var screenshotCanvas;
  8476. var cloneValue = function (source, destinationObject) {
  8477. if (!source)
  8478. return null;
  8479. if (source instanceof BABYLON.Mesh) {
  8480. return null;
  8481. }
  8482. if (source instanceof BABYLON.SubMesh) {
  8483. return source.clone(destinationObject);
  8484. }
  8485. else if (source.clone) {
  8486. return source.clone();
  8487. }
  8488. return null;
  8489. };
  8490. var Tools = /** @class */ (function () {
  8491. function Tools() {
  8492. }
  8493. /**
  8494. * Interpolates between a and b via alpha
  8495. * @param a The lower value (returned when alpha = 0)
  8496. * @param b The upper value (returned when alpha = 1)
  8497. * @param alpha The interpolation-factor
  8498. * @return The mixed value
  8499. */
  8500. Tools.Mix = function (a, b, alpha) {
  8501. return a * (1 - alpha) + b * alpha;
  8502. };
  8503. Tools.Instantiate = function (className) {
  8504. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8505. return Tools.RegisteredExternalClasses[className];
  8506. }
  8507. var arr = className.split(".");
  8508. var fn = (window || this);
  8509. for (var i = 0, len = arr.length; i < len; i++) {
  8510. fn = fn[arr[i]];
  8511. }
  8512. if (typeof fn !== "function") {
  8513. return null;
  8514. }
  8515. return fn;
  8516. };
  8517. /**
  8518. * Provides a slice function that will work even on IE
  8519. * @param data defines the array to slice
  8520. * @param start defines the start of the data (optional)
  8521. * @param end defines the end of the data (optional)
  8522. * @returns the new sliced array
  8523. */
  8524. Tools.Slice = function (data, start, end) {
  8525. if (data.slice) {
  8526. return data.slice(start, end);
  8527. }
  8528. return Array.prototype.slice.call(data, start, end);
  8529. };
  8530. Tools.SetImmediate = function (action) {
  8531. if (window.setImmediate) {
  8532. window.setImmediate(action);
  8533. }
  8534. else {
  8535. setTimeout(action, 1);
  8536. }
  8537. };
  8538. Tools.IsExponentOfTwo = function (value) {
  8539. var count = 1;
  8540. do {
  8541. count *= 2;
  8542. } while (count < value);
  8543. return count === value;
  8544. };
  8545. /**
  8546. * Returns the nearest 32-bit single precision float representation of a Number
  8547. * @param value A Number. If the parameter is of a different type, it will get converted
  8548. * to a number or to NaN if it cannot be converted
  8549. * @returns number
  8550. */
  8551. Tools.FloatRound = function (value) {
  8552. if (Math.fround) {
  8553. return Math.fround(value);
  8554. }
  8555. return (Tools._tmpFloatArray[0] = value);
  8556. };
  8557. /**
  8558. * Find the next highest power of two.
  8559. * @param x Number to start search from.
  8560. * @return Next highest power of two.
  8561. */
  8562. Tools.CeilingPOT = function (x) {
  8563. x--;
  8564. x |= x >> 1;
  8565. x |= x >> 2;
  8566. x |= x >> 4;
  8567. x |= x >> 8;
  8568. x |= x >> 16;
  8569. x++;
  8570. return x;
  8571. };
  8572. /**
  8573. * Find the next lowest power of two.
  8574. * @param x Number to start search from.
  8575. * @return Next lowest power of two.
  8576. */
  8577. Tools.FloorPOT = function (x) {
  8578. x = x | (x >> 1);
  8579. x = x | (x >> 2);
  8580. x = x | (x >> 4);
  8581. x = x | (x >> 8);
  8582. x = x | (x >> 16);
  8583. return x - (x >> 1);
  8584. };
  8585. /**
  8586. * Find the nearest power of two.
  8587. * @param x Number to start search from.
  8588. * @return Next nearest power of two.
  8589. */
  8590. Tools.NearestPOT = function (x) {
  8591. var c = Tools.CeilingPOT(x);
  8592. var f = Tools.FloorPOT(x);
  8593. return (c - x) > (x - f) ? f : c;
  8594. };
  8595. Tools.GetExponentOfTwo = function (value, max, mode) {
  8596. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8597. var pot;
  8598. switch (mode) {
  8599. case BABYLON.Engine.SCALEMODE_FLOOR:
  8600. pot = Tools.FloorPOT(value);
  8601. break;
  8602. case BABYLON.Engine.SCALEMODE_NEAREST:
  8603. pot = Tools.NearestPOT(value);
  8604. break;
  8605. case BABYLON.Engine.SCALEMODE_CEILING:
  8606. default:
  8607. pot = Tools.CeilingPOT(value);
  8608. break;
  8609. }
  8610. return Math.min(pot, max);
  8611. };
  8612. Tools.GetFilename = function (path) {
  8613. var index = path.lastIndexOf("/");
  8614. if (index < 0)
  8615. return path;
  8616. return path.substring(index + 1);
  8617. };
  8618. /**
  8619. * Extracts the "folder" part of a path (everything before the filename).
  8620. * @param uri The URI to extract the info from
  8621. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8622. * @returns The "folder" part of the path
  8623. */
  8624. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8625. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8626. var index = uri.lastIndexOf("/");
  8627. if (index < 0) {
  8628. if (returnUnchangedIfNoSlash) {
  8629. return uri;
  8630. }
  8631. return "";
  8632. }
  8633. return uri.substring(0, index + 1);
  8634. };
  8635. Tools.GetDOMTextContent = function (element) {
  8636. var result = "";
  8637. var child = element.firstChild;
  8638. while (child) {
  8639. if (child.nodeType === 3) {
  8640. result += child.textContent;
  8641. }
  8642. child = child.nextSibling;
  8643. }
  8644. return result;
  8645. };
  8646. Tools.ToDegrees = function (angle) {
  8647. return angle * 180 / Math.PI;
  8648. };
  8649. Tools.ToRadians = function (angle) {
  8650. return angle * Math.PI / 180;
  8651. };
  8652. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8653. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8654. var output = "";
  8655. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8656. var i = 0;
  8657. var bytes = new Uint8Array(buffer);
  8658. while (i < bytes.length) {
  8659. chr1 = bytes[i++];
  8660. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8661. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8662. enc1 = chr1 >> 2;
  8663. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8664. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8665. enc4 = chr3 & 63;
  8666. if (isNaN(chr2)) {
  8667. enc3 = enc4 = 64;
  8668. }
  8669. else if (isNaN(chr3)) {
  8670. enc4 = 64;
  8671. }
  8672. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8673. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8674. }
  8675. return "data:image/png;base64," + output;
  8676. };
  8677. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8678. if (bias === void 0) { bias = null; }
  8679. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8680. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8681. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8682. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8683. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8684. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8685. }
  8686. if (bias) {
  8687. minimum.x -= minimum.x * bias.x + bias.y;
  8688. minimum.y -= minimum.y * bias.x + bias.y;
  8689. minimum.z -= minimum.z * bias.x + bias.y;
  8690. maximum.x += maximum.x * bias.x + bias.y;
  8691. maximum.y += maximum.y * bias.x + bias.y;
  8692. maximum.z += maximum.z * bias.x + bias.y;
  8693. }
  8694. return {
  8695. minimum: minimum,
  8696. maximum: maximum
  8697. };
  8698. };
  8699. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8700. if (bias === void 0) { bias = null; }
  8701. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8702. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8703. if (!stride) {
  8704. stride = 3;
  8705. }
  8706. for (var index = start; index < start + count; index++) {
  8707. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8708. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8709. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8710. }
  8711. if (bias) {
  8712. minimum.x -= minimum.x * bias.x + bias.y;
  8713. minimum.y -= minimum.y * bias.x + bias.y;
  8714. minimum.z -= minimum.z * bias.x + bias.y;
  8715. maximum.x += maximum.x * bias.x + bias.y;
  8716. maximum.y += maximum.y * bias.x + bias.y;
  8717. maximum.z += maximum.z * bias.x + bias.y;
  8718. }
  8719. return {
  8720. minimum: minimum,
  8721. maximum: maximum
  8722. };
  8723. };
  8724. Tools.Vector2ArrayFeeder = function (array) {
  8725. return function (index) {
  8726. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8727. var length = isFloatArray ? array.length / 2 : array.length;
  8728. if (index >= length) {
  8729. return null;
  8730. }
  8731. if (isFloatArray) {
  8732. var fa = array;
  8733. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8734. }
  8735. var a = array;
  8736. return a[index];
  8737. };
  8738. };
  8739. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8740. if (bias === void 0) { bias = null; }
  8741. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8742. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8743. var i = 0;
  8744. var cur = feeder(i++);
  8745. while (cur) {
  8746. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8747. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8748. cur = feeder(i++);
  8749. }
  8750. if (bias) {
  8751. minimum.x -= minimum.x * bias.x + bias.y;
  8752. minimum.y -= minimum.y * bias.x + bias.y;
  8753. maximum.x += maximum.x * bias.x + bias.y;
  8754. maximum.y += maximum.y * bias.x + bias.y;
  8755. }
  8756. return {
  8757. minimum: minimum,
  8758. maximum: maximum
  8759. };
  8760. };
  8761. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8762. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8763. return null;
  8764. return Array.isArray(obj) ? obj : [obj];
  8765. };
  8766. // Misc.
  8767. Tools.GetPointerPrefix = function () {
  8768. var eventPrefix = "pointer";
  8769. // Check if pointer events are supported
  8770. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8771. eventPrefix = "mouse";
  8772. }
  8773. return eventPrefix;
  8774. };
  8775. /**
  8776. * @param func - the function to be called
  8777. * @param requester - the object that will request the next frame. Falls back to window.
  8778. */
  8779. Tools.QueueNewFrame = function (func, requester) {
  8780. if (!Tools.IsWindowObjectExist()) {
  8781. return setTimeout(func, 16);
  8782. }
  8783. if (!requester) {
  8784. requester = window;
  8785. }
  8786. if (requester.requestAnimationFrame) {
  8787. return requester.requestAnimationFrame(func);
  8788. }
  8789. else if (requester.msRequestAnimationFrame) {
  8790. return requester.msRequestAnimationFrame(func);
  8791. }
  8792. else if (requester.webkitRequestAnimationFrame) {
  8793. return requester.webkitRequestAnimationFrame(func);
  8794. }
  8795. else if (requester.mozRequestAnimationFrame) {
  8796. return requester.mozRequestAnimationFrame(func);
  8797. }
  8798. else if (requester.oRequestAnimationFrame) {
  8799. return requester.oRequestAnimationFrame(func);
  8800. }
  8801. else {
  8802. return window.setTimeout(func, 16);
  8803. }
  8804. };
  8805. Tools.RequestFullscreen = function (element) {
  8806. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8807. if (!requestFunction)
  8808. return;
  8809. requestFunction.call(element);
  8810. };
  8811. Tools.ExitFullscreen = function () {
  8812. if (document.exitFullscreen) {
  8813. document.exitFullscreen();
  8814. }
  8815. else if (document.mozCancelFullScreen) {
  8816. document.mozCancelFullScreen();
  8817. }
  8818. else if (document.webkitCancelFullScreen) {
  8819. document.webkitCancelFullScreen();
  8820. }
  8821. else if (document.msCancelFullScreen) {
  8822. document.msCancelFullScreen();
  8823. }
  8824. };
  8825. Tools.SetCorsBehavior = function (url, element) {
  8826. if (url && url.indexOf("data:") === 0) {
  8827. return;
  8828. }
  8829. if (Tools.CorsBehavior) {
  8830. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8831. element.crossOrigin = Tools.CorsBehavior;
  8832. }
  8833. else {
  8834. var result = Tools.CorsBehavior(url);
  8835. if (result) {
  8836. element.crossOrigin = result;
  8837. }
  8838. }
  8839. }
  8840. };
  8841. // External files
  8842. Tools.CleanUrl = function (url) {
  8843. url = url.replace(/#/mg, "%23");
  8844. return url;
  8845. };
  8846. Tools.LoadImage = function (url, onLoad, onError, database) {
  8847. if (url instanceof ArrayBuffer) {
  8848. url = Tools.EncodeArrayBufferTobase64(url);
  8849. }
  8850. url = Tools.CleanUrl(url);
  8851. url = Tools.PreprocessUrl(url);
  8852. var img = new Image();
  8853. Tools.SetCorsBehavior(url, img);
  8854. var loadHandler = function () {
  8855. img.removeEventListener("load", loadHandler);
  8856. img.removeEventListener("error", errorHandler);
  8857. onLoad(img);
  8858. };
  8859. var errorHandler = function (err) {
  8860. img.removeEventListener("load", loadHandler);
  8861. img.removeEventListener("error", errorHandler);
  8862. Tools.Error("Error while trying to load image: " + url);
  8863. if (onError) {
  8864. onError("Error while trying to load image: " + url, err);
  8865. }
  8866. };
  8867. img.addEventListener("load", loadHandler);
  8868. img.addEventListener("error", errorHandler);
  8869. var noIndexedDB = function () {
  8870. img.src = url;
  8871. };
  8872. var loadFromIndexedDB = function () {
  8873. if (database) {
  8874. database.loadImageFromDB(url, img);
  8875. }
  8876. };
  8877. //ANY database to do!
  8878. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8879. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8880. }
  8881. else {
  8882. if (url.indexOf("file:") !== -1) {
  8883. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8884. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8885. try {
  8886. var blobURL;
  8887. try {
  8888. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8889. }
  8890. catch (ex) {
  8891. // Chrome doesn't support oneTimeOnly parameter
  8892. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8893. }
  8894. img.src = blobURL;
  8895. }
  8896. catch (e) {
  8897. img.src = "";
  8898. }
  8899. return img;
  8900. }
  8901. }
  8902. noIndexedDB();
  8903. }
  8904. return img;
  8905. };
  8906. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8907. url = Tools.CleanUrl(url);
  8908. url = Tools.PreprocessUrl(url);
  8909. // If file and file input are set
  8910. if (url.indexOf("file:") !== -1) {
  8911. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8912. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8913. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8914. }
  8915. }
  8916. var loadUrl = Tools.BaseUrl + url;
  8917. var aborted = false;
  8918. var fileRequest = {
  8919. onCompleteObservable: new BABYLON.Observable(),
  8920. abort: function () { return aborted = true; },
  8921. };
  8922. var requestFile = function () {
  8923. var request = new XMLHttpRequest();
  8924. var retryHandle = null;
  8925. fileRequest.abort = function () {
  8926. aborted = true;
  8927. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8928. request.abort();
  8929. }
  8930. if (retryHandle !== null) {
  8931. clearTimeout(retryHandle);
  8932. retryHandle = null;
  8933. }
  8934. };
  8935. var retryLoop = function (retryIndex) {
  8936. request.open('GET', loadUrl, true);
  8937. if (useArrayBuffer) {
  8938. request.responseType = "arraybuffer";
  8939. }
  8940. if (onProgress) {
  8941. request.addEventListener("progress", onProgress);
  8942. }
  8943. var onLoadEnd = function () {
  8944. request.removeEventListener("loadend", onLoadEnd);
  8945. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8946. fileRequest.onCompleteObservable.clear();
  8947. };
  8948. request.addEventListener("loadend", onLoadEnd);
  8949. var onReadyStateChange = function () {
  8950. if (aborted) {
  8951. return;
  8952. }
  8953. // In case of undefined state in some browsers.
  8954. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8955. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8956. request.removeEventListener("readystatechange", onReadyStateChange);
  8957. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8958. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8959. return;
  8960. }
  8961. var retryStrategy = Tools.DefaultRetryStrategy;
  8962. if (retryStrategy) {
  8963. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8964. if (waitTime !== -1) {
  8965. // Prevent the request from completing for retry.
  8966. request.removeEventListener("loadend", onLoadEnd);
  8967. request = new XMLHttpRequest();
  8968. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8969. return;
  8970. }
  8971. }
  8972. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8973. if (onError) {
  8974. onError(request, e);
  8975. }
  8976. else {
  8977. throw e;
  8978. }
  8979. }
  8980. };
  8981. request.addEventListener("readystatechange", onReadyStateChange);
  8982. request.send();
  8983. };
  8984. retryLoop(0);
  8985. };
  8986. // Caching all files
  8987. if (database && database.enableSceneOffline) {
  8988. var noIndexedDB_1 = function () {
  8989. if (!aborted) {
  8990. requestFile();
  8991. }
  8992. };
  8993. var loadFromIndexedDB = function () {
  8994. // TODO: database needs to support aborting and should return a IFileRequest
  8995. if (aborted) {
  8996. return;
  8997. }
  8998. if (database) {
  8999. database.loadFileFromDB(url, function (data) {
  9000. if (!aborted) {
  9001. onSuccess(data);
  9002. }
  9003. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9004. }, onProgress ? function (event) {
  9005. if (!aborted) {
  9006. onProgress(event);
  9007. }
  9008. } : undefined, noIndexedDB_1, useArrayBuffer);
  9009. }
  9010. };
  9011. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9012. }
  9013. else {
  9014. requestFile();
  9015. }
  9016. return fileRequest;
  9017. };
  9018. /**
  9019. * Load a script (identified by an url). When the url returns, the
  9020. * content of this file is added into a new script element, attached to the DOM (body element)
  9021. */
  9022. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9023. var head = document.getElementsByTagName('head')[0];
  9024. var script = document.createElement('script');
  9025. script.type = 'text/javascript';
  9026. script.src = scriptUrl;
  9027. script.onload = function () {
  9028. if (onSuccess) {
  9029. onSuccess();
  9030. }
  9031. };
  9032. script.onerror = function (e) {
  9033. if (onError) {
  9034. onError("Unable to load script '" + scriptUrl + "'", e);
  9035. }
  9036. };
  9037. head.appendChild(script);
  9038. };
  9039. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9040. var reader = new FileReader();
  9041. var request = {
  9042. onCompleteObservable: new BABYLON.Observable(),
  9043. abort: function () { return reader.abort(); },
  9044. };
  9045. reader.onloadend = function (e) {
  9046. request.onCompleteObservable.notifyObservers(request);
  9047. };
  9048. reader.onload = function (e) {
  9049. //target doesn't have result from ts 1.3
  9050. callback(e.target['result']);
  9051. };
  9052. reader.onprogress = progressCallback;
  9053. reader.readAsDataURL(fileToLoad);
  9054. return request;
  9055. };
  9056. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9057. var reader = new FileReader();
  9058. var request = {
  9059. onCompleteObservable: new BABYLON.Observable(),
  9060. abort: function () { return reader.abort(); },
  9061. };
  9062. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9063. reader.onerror = function (e) {
  9064. Tools.Log("Error while reading file: " + fileToLoad.name);
  9065. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9066. };
  9067. reader.onload = function (e) {
  9068. //target doesn't have result from ts 1.3
  9069. callback(e.target['result']);
  9070. };
  9071. if (progressCallBack) {
  9072. reader.onprogress = progressCallBack;
  9073. }
  9074. if (!useArrayBuffer) {
  9075. // Asynchronous read
  9076. reader.readAsText(fileToLoad);
  9077. }
  9078. else {
  9079. reader.readAsArrayBuffer(fileToLoad);
  9080. }
  9081. return request;
  9082. };
  9083. //returns a downloadable url to a file content.
  9084. Tools.FileAsURL = function (content) {
  9085. var fileBlob = new Blob([content]);
  9086. var url = window.URL || window.webkitURL;
  9087. var link = url.createObjectURL(fileBlob);
  9088. return link;
  9089. };
  9090. // Misc.
  9091. Tools.Format = function (value, decimals) {
  9092. if (decimals === void 0) { decimals = 2; }
  9093. return value.toFixed(decimals);
  9094. };
  9095. Tools.CheckExtends = function (v, min, max) {
  9096. if (v.x < min.x)
  9097. min.x = v.x;
  9098. if (v.y < min.y)
  9099. min.y = v.y;
  9100. if (v.z < min.z)
  9101. min.z = v.z;
  9102. if (v.x > max.x)
  9103. max.x = v.x;
  9104. if (v.y > max.y)
  9105. max.y = v.y;
  9106. if (v.z > max.z)
  9107. max.z = v.z;
  9108. };
  9109. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9110. for (var prop in source) {
  9111. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9112. continue;
  9113. }
  9114. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9115. continue;
  9116. }
  9117. var sourceValue = source[prop];
  9118. var typeOfSourceValue = typeof sourceValue;
  9119. if (typeOfSourceValue === "function") {
  9120. continue;
  9121. }
  9122. try {
  9123. if (typeOfSourceValue === "object") {
  9124. if (sourceValue instanceof Array) {
  9125. destination[prop] = [];
  9126. if (sourceValue.length > 0) {
  9127. if (typeof sourceValue[0] == "object") {
  9128. for (var index = 0; index < sourceValue.length; index++) {
  9129. var clonedValue = cloneValue(sourceValue[index], destination);
  9130. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9131. destination[prop].push(clonedValue);
  9132. }
  9133. }
  9134. }
  9135. else {
  9136. destination[prop] = sourceValue.slice(0);
  9137. }
  9138. }
  9139. }
  9140. else {
  9141. destination[prop] = cloneValue(sourceValue, destination);
  9142. }
  9143. }
  9144. else {
  9145. destination[prop] = sourceValue;
  9146. }
  9147. }
  9148. catch (e) {
  9149. // Just ignore error (it could be because of a read-only property)
  9150. }
  9151. }
  9152. };
  9153. Tools.IsEmpty = function (obj) {
  9154. for (var i in obj) {
  9155. if (obj.hasOwnProperty(i)) {
  9156. return false;
  9157. }
  9158. }
  9159. return true;
  9160. };
  9161. Tools.RegisterTopRootEvents = function (events) {
  9162. for (var index = 0; index < events.length; index++) {
  9163. var event = events[index];
  9164. window.addEventListener(event.name, event.handler, false);
  9165. try {
  9166. if (window.parent) {
  9167. window.parent.addEventListener(event.name, event.handler, false);
  9168. }
  9169. }
  9170. catch (e) {
  9171. // Silently fails...
  9172. }
  9173. }
  9174. };
  9175. Tools.UnregisterTopRootEvents = function (events) {
  9176. for (var index = 0; index < events.length; index++) {
  9177. var event = events[index];
  9178. window.removeEventListener(event.name, event.handler);
  9179. try {
  9180. if (window.parent) {
  9181. window.parent.removeEventListener(event.name, event.handler);
  9182. }
  9183. }
  9184. catch (e) {
  9185. // Silently fails...
  9186. }
  9187. }
  9188. };
  9189. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9190. if (mimeType === void 0) { mimeType = "image/png"; }
  9191. // Read the contents of the framebuffer
  9192. var numberOfChannelsByLine = width * 4;
  9193. var halfHeight = height / 2;
  9194. //Reading datas from WebGL
  9195. var data = engine.readPixels(0, 0, width, height);
  9196. //To flip image on Y axis.
  9197. for (var i = 0; i < halfHeight; i++) {
  9198. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9199. var currentCell = j + i * numberOfChannelsByLine;
  9200. var targetLine = height - i - 1;
  9201. var targetCell = j + targetLine * numberOfChannelsByLine;
  9202. var temp = data[currentCell];
  9203. data[currentCell] = data[targetCell];
  9204. data[targetCell] = temp;
  9205. }
  9206. }
  9207. // Create a 2D canvas to store the result
  9208. if (!screenshotCanvas) {
  9209. screenshotCanvas = document.createElement('canvas');
  9210. }
  9211. screenshotCanvas.width = width;
  9212. screenshotCanvas.height = height;
  9213. var context = screenshotCanvas.getContext('2d');
  9214. if (context) {
  9215. // Copy the pixels to a 2D canvas
  9216. var imageData = context.createImageData(width, height);
  9217. var castData = (imageData.data);
  9218. castData.set(data);
  9219. context.putImageData(imageData, 0, 0);
  9220. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9221. }
  9222. };
  9223. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9224. if (mimeType === void 0) { mimeType = "image/png"; }
  9225. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9226. if (successCallback) {
  9227. successCallback(base64Image);
  9228. }
  9229. else {
  9230. // We need HTMLCanvasElement.toBlob for HD screenshots
  9231. if (!screenshotCanvas.toBlob) {
  9232. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9233. screenshotCanvas.toBlob = function (callback, type, quality) {
  9234. var _this = this;
  9235. setTimeout(function () {
  9236. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9237. for (var i = 0; i < len; i++) {
  9238. arr[i] = binStr.charCodeAt(i);
  9239. }
  9240. callback(new Blob([arr], { type: type || 'image/png' }));
  9241. });
  9242. };
  9243. }
  9244. screenshotCanvas.toBlob(function (blob) {
  9245. var url = URL.createObjectURL(blob);
  9246. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9247. if (("download" in document.createElement("a"))) {
  9248. var a = window.document.createElement("a");
  9249. a.href = url;
  9250. if (fileName) {
  9251. a.setAttribute("download", fileName);
  9252. }
  9253. else {
  9254. var date = new Date();
  9255. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9256. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9257. }
  9258. window.document.body.appendChild(a);
  9259. a.addEventListener("click", function () {
  9260. if (a.parentElement) {
  9261. a.parentElement.removeChild(a);
  9262. }
  9263. });
  9264. a.click();
  9265. }
  9266. else {
  9267. var newWindow = window.open("");
  9268. if (!newWindow)
  9269. return;
  9270. var img = newWindow.document.createElement("img");
  9271. img.onload = function () {
  9272. // no longer need to read the blob so it's revoked
  9273. URL.revokeObjectURL(url);
  9274. };
  9275. img.src = url;
  9276. newWindow.document.body.appendChild(img);
  9277. }
  9278. });
  9279. }
  9280. };
  9281. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9282. if (mimeType === void 0) { mimeType = "image/png"; }
  9283. var width;
  9284. var height;
  9285. // If a precision value is specified
  9286. if (size.precision) {
  9287. width = Math.round(engine.getRenderWidth() * size.precision);
  9288. height = Math.round(width / engine.getAspectRatio(camera));
  9289. }
  9290. else if (size.width && size.height) {
  9291. width = size.width;
  9292. height = size.height;
  9293. }
  9294. //If passing only width, computing height to keep display canvas ratio.
  9295. else if (size.width && !size.height) {
  9296. width = size.width;
  9297. height = Math.round(width / engine.getAspectRatio(camera));
  9298. }
  9299. //If passing only height, computing width to keep display canvas ratio.
  9300. else if (size.height && !size.width) {
  9301. height = size.height;
  9302. width = Math.round(height * engine.getAspectRatio(camera));
  9303. }
  9304. //Assuming here that "size" parameter is a number
  9305. else if (!isNaN(size)) {
  9306. height = size;
  9307. width = size;
  9308. }
  9309. else {
  9310. Tools.Error("Invalid 'size' parameter !");
  9311. return;
  9312. }
  9313. if (!screenshotCanvas) {
  9314. screenshotCanvas = document.createElement('canvas');
  9315. }
  9316. screenshotCanvas.width = width;
  9317. screenshotCanvas.height = height;
  9318. var renderContext = screenshotCanvas.getContext("2d");
  9319. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9320. var newWidth = width;
  9321. var newHeight = newWidth / ratio;
  9322. if (newHeight > height) {
  9323. newHeight = height;
  9324. newWidth = newHeight * ratio;
  9325. }
  9326. var offsetX = Math.max(0, width - newWidth) / 2;
  9327. var offsetY = Math.max(0, height - newHeight) / 2;
  9328. var renderingCanvas = engine.getRenderingCanvas();
  9329. if (renderContext && renderingCanvas) {
  9330. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9331. }
  9332. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9333. };
  9334. /**
  9335. * Generates an image screenshot from the specified camera.
  9336. *
  9337. * @param engine The engine to use for rendering
  9338. * @param camera The camera to use for rendering
  9339. * @param size This parameter can be set to a single number or to an object with the
  9340. * following (optional) properties: precision, width, height. If a single number is passed,
  9341. * it will be used for both width and height. If an object is passed, the screenshot size
  9342. * will be derived from the parameters. The precision property is a multiplier allowing
  9343. * rendering at a higher or lower resolution.
  9344. * @param successCallback The callback receives a single parameter which contains the
  9345. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9346. * src parameter of an <img> to display it.
  9347. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9348. * Check your browser for supported MIME types.
  9349. * @param samples Texture samples (default: 1)
  9350. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9351. * @param fileName A name for for the downloaded file.
  9352. * @constructor
  9353. */
  9354. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9355. if (mimeType === void 0) { mimeType = "image/png"; }
  9356. if (samples === void 0) { samples = 1; }
  9357. if (antialiasing === void 0) { antialiasing = false; }
  9358. var width;
  9359. var height;
  9360. //If a precision value is specified
  9361. if (size.precision) {
  9362. width = Math.round(engine.getRenderWidth() * size.precision);
  9363. height = Math.round(width / engine.getAspectRatio(camera));
  9364. size = { width: width, height: height };
  9365. }
  9366. else if (size.width && size.height) {
  9367. width = size.width;
  9368. height = size.height;
  9369. }
  9370. //If passing only width, computing height to keep display canvas ratio.
  9371. else if (size.width && !size.height) {
  9372. width = size.width;
  9373. height = Math.round(width / engine.getAspectRatio(camera));
  9374. size = { width: width, height: height };
  9375. }
  9376. //If passing only height, computing width to keep display canvas ratio.
  9377. else if (size.height && !size.width) {
  9378. height = size.height;
  9379. width = Math.round(height * engine.getAspectRatio(camera));
  9380. size = { width: width, height: height };
  9381. }
  9382. //Assuming here that "size" parameter is a number
  9383. else if (!isNaN(size)) {
  9384. height = size;
  9385. width = size;
  9386. }
  9387. else {
  9388. Tools.Error("Invalid 'size' parameter !");
  9389. return;
  9390. }
  9391. var scene = camera.getScene();
  9392. var previousCamera = null;
  9393. if (scene.activeCamera !== camera) {
  9394. previousCamera = scene.activeCamera;
  9395. scene.activeCamera = camera;
  9396. }
  9397. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9398. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9399. texture.renderList = null;
  9400. texture.samples = samples;
  9401. if (antialiasing) {
  9402. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9403. }
  9404. texture.onAfterRenderObservable.add(function () {
  9405. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9406. });
  9407. scene.incrementRenderId();
  9408. scene.resetCachedMaterial();
  9409. texture.render(true);
  9410. texture.dispose();
  9411. if (previousCamera) {
  9412. scene.activeCamera = previousCamera;
  9413. }
  9414. camera.getProjectionMatrix(true); // Force cache refresh;
  9415. };
  9416. // XHR response validator for local file scenario
  9417. Tools.ValidateXHRData = function (xhr, dataType) {
  9418. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9419. if (dataType === void 0) { dataType = 7; }
  9420. try {
  9421. if (dataType & 1) {
  9422. if (xhr.responseText && xhr.responseText.length > 0) {
  9423. return true;
  9424. }
  9425. else if (dataType === 1) {
  9426. return false;
  9427. }
  9428. }
  9429. if (dataType & 2) {
  9430. // Check header width and height since there is no "TGA" magic number
  9431. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9432. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9433. return true;
  9434. }
  9435. else if (dataType === 2) {
  9436. return false;
  9437. }
  9438. }
  9439. if (dataType & 4) {
  9440. // Check for the "DDS" magic number
  9441. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9442. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9443. return true;
  9444. }
  9445. else {
  9446. return false;
  9447. }
  9448. }
  9449. }
  9450. catch (e) {
  9451. // Global protection
  9452. }
  9453. return false;
  9454. };
  9455. /**
  9456. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9457. * Be aware Math.random() could cause collisions, but:
  9458. * "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"
  9459. */
  9460. Tools.RandomId = function () {
  9461. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9462. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9463. return v.toString(16);
  9464. });
  9465. };
  9466. /**
  9467. * Test if the given uri is a base64 string.
  9468. * @param uri The uri to test
  9469. * @return True if the uri is a base64 string or false otherwise.
  9470. */
  9471. Tools.IsBase64 = function (uri) {
  9472. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9473. };
  9474. /**
  9475. * Decode the given base64 uri.
  9476. * @param uri The uri to decode
  9477. * @return The decoded base64 data.
  9478. */
  9479. Tools.DecodeBase64 = function (uri) {
  9480. var decodedString = atob(uri.split(",")[1]);
  9481. var bufferLength = decodedString.length;
  9482. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9483. for (var i = 0; i < bufferLength; i++) {
  9484. bufferView[i] = decodedString.charCodeAt(i);
  9485. }
  9486. return bufferView.buffer;
  9487. };
  9488. Object.defineProperty(Tools, "NoneLogLevel", {
  9489. get: function () {
  9490. return Tools._NoneLogLevel;
  9491. },
  9492. enumerable: true,
  9493. configurable: true
  9494. });
  9495. Object.defineProperty(Tools, "MessageLogLevel", {
  9496. get: function () {
  9497. return Tools._MessageLogLevel;
  9498. },
  9499. enumerable: true,
  9500. configurable: true
  9501. });
  9502. Object.defineProperty(Tools, "WarningLogLevel", {
  9503. get: function () {
  9504. return Tools._WarningLogLevel;
  9505. },
  9506. enumerable: true,
  9507. configurable: true
  9508. });
  9509. Object.defineProperty(Tools, "ErrorLogLevel", {
  9510. get: function () {
  9511. return Tools._ErrorLogLevel;
  9512. },
  9513. enumerable: true,
  9514. configurable: true
  9515. });
  9516. Object.defineProperty(Tools, "AllLogLevel", {
  9517. get: function () {
  9518. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9519. },
  9520. enumerable: true,
  9521. configurable: true
  9522. });
  9523. Tools._AddLogEntry = function (entry) {
  9524. Tools._LogCache = entry + Tools._LogCache;
  9525. if (Tools.OnNewCacheEntry) {
  9526. Tools.OnNewCacheEntry(entry);
  9527. }
  9528. };
  9529. Tools._FormatMessage = function (message) {
  9530. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9531. var date = new Date();
  9532. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9533. };
  9534. Tools._LogDisabled = function (message) {
  9535. // nothing to do
  9536. };
  9537. Tools._LogEnabled = function (message) {
  9538. var formattedMessage = Tools._FormatMessage(message);
  9539. console.log("BJS - " + formattedMessage);
  9540. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9541. Tools._AddLogEntry(entry);
  9542. };
  9543. Tools._WarnDisabled = function (message) {
  9544. // nothing to do
  9545. };
  9546. Tools._WarnEnabled = function (message) {
  9547. var formattedMessage = Tools._FormatMessage(message);
  9548. console.warn("BJS - " + formattedMessage);
  9549. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9550. Tools._AddLogEntry(entry);
  9551. };
  9552. Tools._ErrorDisabled = function (message) {
  9553. // nothing to do
  9554. };
  9555. Tools._ErrorEnabled = function (message) {
  9556. Tools.errorsCount++;
  9557. var formattedMessage = Tools._FormatMessage(message);
  9558. console.error("BJS - " + formattedMessage);
  9559. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9560. Tools._AddLogEntry(entry);
  9561. };
  9562. Object.defineProperty(Tools, "LogCache", {
  9563. get: function () {
  9564. return Tools._LogCache;
  9565. },
  9566. enumerable: true,
  9567. configurable: true
  9568. });
  9569. Tools.ClearLogCache = function () {
  9570. Tools._LogCache = "";
  9571. Tools.errorsCount = 0;
  9572. };
  9573. Object.defineProperty(Tools, "LogLevels", {
  9574. set: function (level) {
  9575. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9576. Tools.Log = Tools._LogEnabled;
  9577. }
  9578. else {
  9579. Tools.Log = Tools._LogDisabled;
  9580. }
  9581. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9582. Tools.Warn = Tools._WarnEnabled;
  9583. }
  9584. else {
  9585. Tools.Warn = Tools._WarnDisabled;
  9586. }
  9587. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9588. Tools.Error = Tools._ErrorEnabled;
  9589. }
  9590. else {
  9591. Tools.Error = Tools._ErrorDisabled;
  9592. }
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. Tools.IsWindowObjectExist = function () {
  9598. return (typeof window) !== "undefined";
  9599. };
  9600. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9601. get: function () {
  9602. return Tools._PerformanceNoneLogLevel;
  9603. },
  9604. enumerable: true,
  9605. configurable: true
  9606. });
  9607. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9608. get: function () {
  9609. return Tools._PerformanceUserMarkLogLevel;
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9615. get: function () {
  9616. return Tools._PerformanceConsoleLogLevel;
  9617. },
  9618. enumerable: true,
  9619. configurable: true
  9620. });
  9621. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9622. set: function (level) {
  9623. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9624. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9625. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9626. return;
  9627. }
  9628. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9629. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9630. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9631. return;
  9632. }
  9633. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9634. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9635. },
  9636. enumerable: true,
  9637. configurable: true
  9638. });
  9639. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9640. };
  9641. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9642. };
  9643. Tools._StartUserMark = function (counterName, condition) {
  9644. if (condition === void 0) { condition = true; }
  9645. if (!Tools._performance) {
  9646. if (!Tools.IsWindowObjectExist()) {
  9647. return;
  9648. }
  9649. Tools._performance = window.performance;
  9650. }
  9651. if (!condition || !Tools._performance.mark) {
  9652. return;
  9653. }
  9654. Tools._performance.mark(counterName + "-Begin");
  9655. };
  9656. Tools._EndUserMark = function (counterName, condition) {
  9657. if (condition === void 0) { condition = true; }
  9658. if (!condition || !Tools._performance.mark) {
  9659. return;
  9660. }
  9661. Tools._performance.mark(counterName + "-End");
  9662. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9663. };
  9664. Tools._StartPerformanceConsole = function (counterName, condition) {
  9665. if (condition === void 0) { condition = true; }
  9666. if (!condition) {
  9667. return;
  9668. }
  9669. Tools._StartUserMark(counterName, condition);
  9670. if (console.time) {
  9671. console.time(counterName);
  9672. }
  9673. };
  9674. Tools._EndPerformanceConsole = function (counterName, condition) {
  9675. if (condition === void 0) { condition = true; }
  9676. if (!condition) {
  9677. return;
  9678. }
  9679. Tools._EndUserMark(counterName, condition);
  9680. if (console.time) {
  9681. console.timeEnd(counterName);
  9682. }
  9683. };
  9684. Object.defineProperty(Tools, "Now", {
  9685. get: function () {
  9686. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9687. return window.performance.now();
  9688. }
  9689. return Date.now();
  9690. },
  9691. enumerable: true,
  9692. configurable: true
  9693. });
  9694. /**
  9695. * This method will return the name of the class used to create the instance of the given object.
  9696. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9697. * @param object the object to get the class name from
  9698. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9699. */
  9700. Tools.GetClassName = function (object, isType) {
  9701. if (isType === void 0) { isType = false; }
  9702. var name = null;
  9703. if (!isType && object.getClassName) {
  9704. name = object.getClassName();
  9705. }
  9706. else {
  9707. if (object instanceof Object) {
  9708. var classObj = isType ? object : Object.getPrototypeOf(object);
  9709. name = classObj.constructor["__bjsclassName__"];
  9710. }
  9711. if (!name) {
  9712. name = typeof object;
  9713. }
  9714. }
  9715. return name;
  9716. };
  9717. Tools.First = function (array, predicate) {
  9718. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9719. var el = array_1[_i];
  9720. if (predicate(el)) {
  9721. return el;
  9722. }
  9723. }
  9724. return null;
  9725. };
  9726. /**
  9727. * This method will return the name of the full name of the class, including its owning module (if any).
  9728. * 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).
  9729. * @param object the object to get the class name from
  9730. * @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.
  9731. */
  9732. Tools.getFullClassName = function (object, isType) {
  9733. if (isType === void 0) { isType = false; }
  9734. var className = null;
  9735. var moduleName = null;
  9736. if (!isType && object.getClassName) {
  9737. className = object.getClassName();
  9738. }
  9739. else {
  9740. if (object instanceof Object) {
  9741. var classObj = isType ? object : Object.getPrototypeOf(object);
  9742. className = classObj.constructor["__bjsclassName__"];
  9743. moduleName = classObj.constructor["__bjsmoduleName__"];
  9744. }
  9745. if (!className) {
  9746. className = typeof object;
  9747. }
  9748. }
  9749. if (!className) {
  9750. return null;
  9751. }
  9752. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9753. };
  9754. /**
  9755. * 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.
  9756. * @param array
  9757. */
  9758. Tools.arrayOrStringFeeder = function (array) {
  9759. return function (index) {
  9760. if (index >= array.length) {
  9761. return null;
  9762. }
  9763. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9764. if (val && val.getHashCode) {
  9765. val = val.getHashCode();
  9766. }
  9767. if (typeof val === "string") {
  9768. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9769. }
  9770. return val;
  9771. };
  9772. };
  9773. /**
  9774. * Compute the hashCode of a stream of number
  9775. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9776. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9777. * @return the hash code computed
  9778. */
  9779. Tools.hashCodeFromStream = function (feeder) {
  9780. // Based from here: http://stackoverflow.com/a/7616484/802124
  9781. var hash = 0;
  9782. var index = 0;
  9783. var chr = feeder(index++);
  9784. while (chr != null) {
  9785. hash = ((hash << 5) - hash) + chr;
  9786. hash |= 0; // Convert to 32bit integer
  9787. chr = feeder(index++);
  9788. }
  9789. return hash;
  9790. };
  9791. /**
  9792. * Returns a promise that resolves after the given amount of time.
  9793. * @param delay Number of milliseconds to delay
  9794. * @returns Promise that resolves after the given amount of time
  9795. */
  9796. Tools.DelayAsync = function (delay) {
  9797. return new Promise(function (resolve) {
  9798. setTimeout(function () {
  9799. resolve();
  9800. }, delay);
  9801. });
  9802. };
  9803. Tools.BaseUrl = "";
  9804. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9805. /**
  9806. * Default behaviour for cors in the application.
  9807. * It can be a string if the expected behavior is identical in the entire app.
  9808. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9809. */
  9810. Tools.CorsBehavior = "anonymous";
  9811. Tools.UseFallbackTexture = true;
  9812. /**
  9813. * Use this object to register external classes like custom textures or material
  9814. * to allow the laoders to instantiate them
  9815. */
  9816. Tools.RegisteredExternalClasses = {};
  9817. // Used in case of a texture loading problem
  9818. 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";
  9819. Tools._tmpFloatArray = new Float32Array(1);
  9820. Tools.PreprocessUrl = function (url) {
  9821. return url;
  9822. };
  9823. // Logs
  9824. Tools._NoneLogLevel = 0;
  9825. Tools._MessageLogLevel = 1;
  9826. Tools._WarningLogLevel = 2;
  9827. Tools._ErrorLogLevel = 4;
  9828. Tools._LogCache = "";
  9829. Tools.errorsCount = 0;
  9830. Tools.Log = Tools._LogEnabled;
  9831. Tools.Warn = Tools._WarnEnabled;
  9832. Tools.Error = Tools._ErrorEnabled;
  9833. // Performances
  9834. Tools._PerformanceNoneLogLevel = 0;
  9835. Tools._PerformanceUserMarkLogLevel = 1;
  9836. Tools._PerformanceConsoleLogLevel = 2;
  9837. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9838. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9839. return Tools;
  9840. }());
  9841. BABYLON.Tools = Tools;
  9842. /**
  9843. * This class is used to track a performance counter which is number based.
  9844. * The user has access to many properties which give statistics of different nature
  9845. *
  9846. * The implementer can track two kinds of Performance Counter: time and count
  9847. * 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.
  9848. * 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.
  9849. */
  9850. var PerfCounter = /** @class */ (function () {
  9851. function PerfCounter() {
  9852. this._startMonitoringTime = 0;
  9853. this._min = 0;
  9854. this._max = 0;
  9855. this._average = 0;
  9856. this._lastSecAverage = 0;
  9857. this._current = 0;
  9858. this._totalValueCount = 0;
  9859. this._totalAccumulated = 0;
  9860. this._lastSecAccumulated = 0;
  9861. this._lastSecTime = 0;
  9862. this._lastSecValueCount = 0;
  9863. }
  9864. Object.defineProperty(PerfCounter.prototype, "min", {
  9865. /**
  9866. * Returns the smallest value ever
  9867. */
  9868. get: function () {
  9869. return this._min;
  9870. },
  9871. enumerable: true,
  9872. configurable: true
  9873. });
  9874. Object.defineProperty(PerfCounter.prototype, "max", {
  9875. /**
  9876. * Returns the biggest value ever
  9877. */
  9878. get: function () {
  9879. return this._max;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(PerfCounter.prototype, "average", {
  9885. /**
  9886. * Returns the average value since the performance counter is running
  9887. */
  9888. get: function () {
  9889. return this._average;
  9890. },
  9891. enumerable: true,
  9892. configurable: true
  9893. });
  9894. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9895. /**
  9896. * Returns the average value of the last second the counter was monitored
  9897. */
  9898. get: function () {
  9899. return this._lastSecAverage;
  9900. },
  9901. enumerable: true,
  9902. configurable: true
  9903. });
  9904. Object.defineProperty(PerfCounter.prototype, "current", {
  9905. /**
  9906. * Returns the current value
  9907. */
  9908. get: function () {
  9909. return this._current;
  9910. },
  9911. enumerable: true,
  9912. configurable: true
  9913. });
  9914. Object.defineProperty(PerfCounter.prototype, "total", {
  9915. get: function () {
  9916. return this._totalAccumulated;
  9917. },
  9918. enumerable: true,
  9919. configurable: true
  9920. });
  9921. Object.defineProperty(PerfCounter.prototype, "count", {
  9922. get: function () {
  9923. return this._totalValueCount;
  9924. },
  9925. enumerable: true,
  9926. configurable: true
  9927. });
  9928. /**
  9929. * Call this method to start monitoring a new frame.
  9930. * 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.
  9931. */
  9932. PerfCounter.prototype.fetchNewFrame = function () {
  9933. this._totalValueCount++;
  9934. this._current = 0;
  9935. this._lastSecValueCount++;
  9936. };
  9937. /**
  9938. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9939. * @param newCount the count value to add to the monitored count
  9940. * @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.
  9941. */
  9942. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9943. if (!PerfCounter.Enabled) {
  9944. return;
  9945. }
  9946. this._current += newCount;
  9947. if (fetchResult) {
  9948. this._fetchResult();
  9949. }
  9950. };
  9951. /**
  9952. * Start monitoring this performance counter
  9953. */
  9954. PerfCounter.prototype.beginMonitoring = function () {
  9955. if (!PerfCounter.Enabled) {
  9956. return;
  9957. }
  9958. this._startMonitoringTime = Tools.Now;
  9959. };
  9960. /**
  9961. * Compute the time lapsed since the previous beginMonitoring() call.
  9962. * @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
  9963. */
  9964. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9965. if (newFrame === void 0) { newFrame = true; }
  9966. if (!PerfCounter.Enabled) {
  9967. return;
  9968. }
  9969. if (newFrame) {
  9970. this.fetchNewFrame();
  9971. }
  9972. var currentTime = Tools.Now;
  9973. this._current = currentTime - this._startMonitoringTime;
  9974. if (newFrame) {
  9975. this._fetchResult();
  9976. }
  9977. };
  9978. PerfCounter.prototype._fetchResult = function () {
  9979. this._totalAccumulated += this._current;
  9980. this._lastSecAccumulated += this._current;
  9981. // Min/Max update
  9982. this._min = Math.min(this._min, this._current);
  9983. this._max = Math.max(this._max, this._current);
  9984. this._average = this._totalAccumulated / this._totalValueCount;
  9985. // Reset last sec?
  9986. var now = Tools.Now;
  9987. if ((now - this._lastSecTime) > 1000) {
  9988. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9989. this._lastSecTime = now;
  9990. this._lastSecAccumulated = 0;
  9991. this._lastSecValueCount = 0;
  9992. }
  9993. };
  9994. PerfCounter.Enabled = true;
  9995. return PerfCounter;
  9996. }());
  9997. BABYLON.PerfCounter = PerfCounter;
  9998. /**
  9999. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10000. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10001. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10002. * @param name The name of the class, case should be preserved
  10003. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10004. */
  10005. function className(name, module) {
  10006. return function (target) {
  10007. target["__bjsclassName__"] = name;
  10008. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10009. };
  10010. }
  10011. BABYLON.className = className;
  10012. /**
  10013. * An implementation of a loop for asynchronous functions.
  10014. */
  10015. var AsyncLoop = /** @class */ (function () {
  10016. /**
  10017. * Constroctor.
  10018. * @param iterations the number of iterations.
  10019. * @param _fn the function to run each iteration
  10020. * @param _successCallback the callback that will be called upon succesful execution
  10021. * @param offset starting offset.
  10022. */
  10023. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10024. if (offset === void 0) { offset = 0; }
  10025. this.iterations = iterations;
  10026. this._fn = _fn;
  10027. this._successCallback = _successCallback;
  10028. this.index = offset - 1;
  10029. this._done = false;
  10030. }
  10031. /**
  10032. * Execute the next iteration. Must be called after the last iteration was finished.
  10033. */
  10034. AsyncLoop.prototype.executeNext = function () {
  10035. if (!this._done) {
  10036. if (this.index + 1 < this.iterations) {
  10037. ++this.index;
  10038. this._fn(this);
  10039. }
  10040. else {
  10041. this.breakLoop();
  10042. }
  10043. }
  10044. };
  10045. /**
  10046. * Break the loop and run the success callback.
  10047. */
  10048. AsyncLoop.prototype.breakLoop = function () {
  10049. this._done = true;
  10050. this._successCallback();
  10051. };
  10052. /**
  10053. * Helper function
  10054. */
  10055. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10056. if (offset === void 0) { offset = 0; }
  10057. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10058. loop.executeNext();
  10059. return loop;
  10060. };
  10061. /**
  10062. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10063. * @param iterations total number of iterations
  10064. * @param syncedIterations number of synchronous iterations in each async iteration.
  10065. * @param fn the function to call each iteration.
  10066. * @param callback a success call back that will be called when iterating stops.
  10067. * @param breakFunction a break condition (optional)
  10068. * @param timeout timeout settings for the setTimeout function. default - 0.
  10069. * @constructor
  10070. */
  10071. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10072. if (timeout === void 0) { timeout = 0; }
  10073. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10074. if (breakFunction && breakFunction())
  10075. loop.breakLoop();
  10076. else {
  10077. setTimeout(function () {
  10078. for (var i = 0; i < syncedIterations; ++i) {
  10079. var iteration = (loop.index * syncedIterations) + i;
  10080. if (iteration >= iterations)
  10081. break;
  10082. fn(iteration);
  10083. if (breakFunction && breakFunction()) {
  10084. loop.breakLoop();
  10085. break;
  10086. }
  10087. }
  10088. loop.executeNext();
  10089. }, timeout);
  10090. }
  10091. }, callback);
  10092. };
  10093. return AsyncLoop;
  10094. }());
  10095. BABYLON.AsyncLoop = AsyncLoop;
  10096. })(BABYLON || (BABYLON = {}));
  10097. //# sourceMappingURL=babylon.tools.js.map
  10098. var BABYLON;
  10099. (function (BABYLON) {
  10100. var PromiseStates;
  10101. (function (PromiseStates) {
  10102. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10103. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10104. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10105. })(PromiseStates || (PromiseStates = {}));
  10106. var FulFillmentAgregator = /** @class */ (function () {
  10107. function FulFillmentAgregator() {
  10108. this.count = 0;
  10109. this.target = 0;
  10110. this.results = [];
  10111. }
  10112. return FulFillmentAgregator;
  10113. }());
  10114. var InternalPromise = /** @class */ (function () {
  10115. function InternalPromise(resolver) {
  10116. var _this = this;
  10117. this._state = PromiseStates.Pending;
  10118. this._children = new Array();
  10119. this._rejectWasConsumed = false;
  10120. if (!resolver) {
  10121. return;
  10122. }
  10123. try {
  10124. resolver(function (value) {
  10125. _this._resolve(value);
  10126. }, function (reason) {
  10127. _this._reject(reason);
  10128. });
  10129. }
  10130. catch (e) {
  10131. this._reject(e);
  10132. }
  10133. }
  10134. Object.defineProperty(InternalPromise.prototype, "_result", {
  10135. get: function () {
  10136. return this._resultValue;
  10137. },
  10138. set: function (value) {
  10139. this._resultValue = value;
  10140. if (this._parent && this._parent._result === undefined) {
  10141. this._parent._result = value;
  10142. }
  10143. },
  10144. enumerable: true,
  10145. configurable: true
  10146. });
  10147. InternalPromise.prototype.catch = function (onRejected) {
  10148. return this.then(undefined, onRejected);
  10149. };
  10150. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10151. var _this = this;
  10152. var newPromise = new InternalPromise();
  10153. newPromise._onFulfilled = onFulfilled;
  10154. newPromise._onRejected = onRejected;
  10155. // Composition
  10156. this._children.push(newPromise);
  10157. newPromise._parent = this;
  10158. if (this._state !== PromiseStates.Pending) {
  10159. BABYLON.Tools.SetImmediate(function () {
  10160. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10161. var returnedValue = newPromise._resolve(_this._result);
  10162. if (returnedValue !== undefined && returnedValue !== null) {
  10163. if (returnedValue._state !== undefined) {
  10164. var returnedPromise = returnedValue;
  10165. newPromise._children.push(returnedPromise);
  10166. returnedPromise._parent = newPromise;
  10167. newPromise = returnedPromise;
  10168. }
  10169. else {
  10170. newPromise._result = returnedValue;
  10171. }
  10172. }
  10173. }
  10174. else {
  10175. newPromise._reject(_this._reason);
  10176. }
  10177. });
  10178. }
  10179. return newPromise;
  10180. };
  10181. InternalPromise.prototype._moveChildren = function (children) {
  10182. var _this = this;
  10183. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10184. this._children.forEach(function (child) {
  10185. child._parent = _this;
  10186. });
  10187. if (this._state === PromiseStates.Fulfilled) {
  10188. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10189. var child = _b[_i];
  10190. child._resolve(this._result);
  10191. }
  10192. }
  10193. else if (this._state === PromiseStates.Rejected) {
  10194. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10195. var child = _d[_c];
  10196. child._reject(this._reason);
  10197. }
  10198. }
  10199. var _a;
  10200. };
  10201. InternalPromise.prototype._resolve = function (value) {
  10202. try {
  10203. this._state = PromiseStates.Fulfilled;
  10204. var returnedValue = null;
  10205. if (this._onFulfilled) {
  10206. returnedValue = this._onFulfilled(value);
  10207. }
  10208. if (returnedValue !== undefined && returnedValue !== null) {
  10209. if (returnedValue._state !== undefined) {
  10210. // Transmit children
  10211. var returnedPromise = returnedValue;
  10212. returnedPromise._parent = this;
  10213. returnedPromise._moveChildren(this._children);
  10214. value = returnedPromise._result;
  10215. }
  10216. else {
  10217. value = returnedValue;
  10218. }
  10219. }
  10220. this._result = value;
  10221. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10222. var child = _a[_i];
  10223. child._resolve(value);
  10224. }
  10225. this._children.length = 0;
  10226. delete this._onFulfilled;
  10227. delete this._onRejected;
  10228. }
  10229. catch (e) {
  10230. this._reject(e, true);
  10231. }
  10232. };
  10233. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10234. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10235. this._state = PromiseStates.Rejected;
  10236. this._reason = reason;
  10237. if (this._onRejected && !onLocalThrow) {
  10238. try {
  10239. this._onRejected(reason);
  10240. this._rejectWasConsumed = true;
  10241. }
  10242. catch (e) {
  10243. reason = e;
  10244. }
  10245. }
  10246. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10247. var child = _a[_i];
  10248. if (this._rejectWasConsumed) {
  10249. child._resolve(null);
  10250. }
  10251. else {
  10252. child._reject(reason);
  10253. }
  10254. }
  10255. this._children.length = 0;
  10256. delete this._onFulfilled;
  10257. delete this._onRejected;
  10258. };
  10259. InternalPromise.resolve = function (value) {
  10260. var newPromise = new InternalPromise();
  10261. newPromise._resolve(value);
  10262. return newPromise;
  10263. };
  10264. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10265. promise.then(function (value) {
  10266. agregator.results[index] = value;
  10267. agregator.count++;
  10268. if (agregator.count === agregator.target) {
  10269. agregator.rootPromise._resolve(agregator.results);
  10270. }
  10271. return null;
  10272. }, function (reason) {
  10273. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10274. agregator.rootPromise._reject(reason);
  10275. }
  10276. });
  10277. };
  10278. InternalPromise.all = function (promises) {
  10279. var newPromise = new InternalPromise();
  10280. var agregator = new FulFillmentAgregator();
  10281. agregator.target = promises.length;
  10282. agregator.rootPromise = newPromise;
  10283. if (promises.length) {
  10284. for (var index = 0; index < promises.length; index++) {
  10285. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10286. }
  10287. }
  10288. else {
  10289. newPromise._resolve([]);
  10290. }
  10291. return newPromise;
  10292. };
  10293. InternalPromise.race = function (promises) {
  10294. var newPromise = new InternalPromise();
  10295. if (promises.length) {
  10296. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10297. var promise = promises_1[_i];
  10298. promise.then(function (value) {
  10299. if (newPromise) {
  10300. newPromise._resolve(value);
  10301. newPromise = null;
  10302. }
  10303. return null;
  10304. }, function (reason) {
  10305. if (newPromise) {
  10306. newPromise._reject(reason);
  10307. newPromise = null;
  10308. }
  10309. });
  10310. }
  10311. }
  10312. return newPromise;
  10313. };
  10314. return InternalPromise;
  10315. }());
  10316. /**
  10317. * Helper class that provides a small promise polyfill
  10318. */
  10319. var PromisePolyfill = /** @class */ (function () {
  10320. function PromisePolyfill() {
  10321. }
  10322. /**
  10323. * Static function used to check if the polyfill is required
  10324. * If this is the case then the function will inject the polyfill to window.Promise
  10325. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10326. */
  10327. PromisePolyfill.Apply = function (force) {
  10328. if (force === void 0) { force = false; }
  10329. if (force || typeof Promise === 'undefined') {
  10330. var root = window;
  10331. root.Promise = InternalPromise;
  10332. }
  10333. };
  10334. return PromisePolyfill;
  10335. }());
  10336. BABYLON.PromisePolyfill = PromisePolyfill;
  10337. })(BABYLON || (BABYLON = {}));
  10338. //# sourceMappingURL=babylon.promise.js.map
  10339. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10340. var BABYLON;
  10341. (function (BABYLON) {
  10342. /**
  10343. * Helper class to push actions to a pool of workers.
  10344. */
  10345. var WorkerPool = /** @class */ (function () {
  10346. /**
  10347. * Constructor
  10348. * @param workers Array of workers to use for actions
  10349. */
  10350. function WorkerPool(workers) {
  10351. this._pendingActions = new Array();
  10352. this._workerInfos = workers.map(function (worker) { return ({
  10353. worker: worker,
  10354. active: false
  10355. }); });
  10356. }
  10357. /**
  10358. * Terminates all workers and clears any pending actions.
  10359. */
  10360. WorkerPool.prototype.dispose = function () {
  10361. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10362. var workerInfo = _a[_i];
  10363. workerInfo.worker.terminate();
  10364. }
  10365. delete this._workerInfos;
  10366. delete this._pendingActions;
  10367. };
  10368. /**
  10369. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10370. * pended until a worker has completed its action.
  10371. * @param action The action to perform. Call onComplete when the action is complete.
  10372. */
  10373. WorkerPool.prototype.push = function (action) {
  10374. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10375. var workerInfo = _a[_i];
  10376. if (!workerInfo.active) {
  10377. this._execute(workerInfo, action);
  10378. return;
  10379. }
  10380. }
  10381. this._pendingActions.push(action);
  10382. };
  10383. WorkerPool.prototype._execute = function (workerInfo, action) {
  10384. var _this = this;
  10385. workerInfo.active = true;
  10386. action(workerInfo.worker, function () {
  10387. workerInfo.active = false;
  10388. var nextAction = _this._pendingActions.shift();
  10389. if (nextAction) {
  10390. _this._execute(workerInfo, nextAction);
  10391. }
  10392. });
  10393. };
  10394. return WorkerPool;
  10395. }());
  10396. BABYLON.WorkerPool = WorkerPool;
  10397. })(BABYLON || (BABYLON = {}));
  10398. //# sourceMappingURL=babylon.workerPool.js.map
  10399. var BABYLON;
  10400. (function (BABYLON) {
  10401. /**
  10402. * @hidden
  10403. **/
  10404. var _AlphaState = /** @class */ (function () {
  10405. /**
  10406. * Initializes the state.
  10407. */
  10408. function _AlphaState() {
  10409. this._isAlphaBlendDirty = false;
  10410. this._isBlendFunctionParametersDirty = false;
  10411. this._isBlendEquationParametersDirty = false;
  10412. this._isBlendConstantsDirty = false;
  10413. this._alphaBlend = false;
  10414. this._blendFunctionParameters = new Array(4);
  10415. this._blendEquationParameters = new Array(2);
  10416. this._blendConstants = new Array(4);
  10417. this.reset();
  10418. }
  10419. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10420. get: function () {
  10421. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10422. },
  10423. enumerable: true,
  10424. configurable: true
  10425. });
  10426. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10427. get: function () {
  10428. return this._alphaBlend;
  10429. },
  10430. set: function (value) {
  10431. if (this._alphaBlend === value) {
  10432. return;
  10433. }
  10434. this._alphaBlend = value;
  10435. this._isAlphaBlendDirty = true;
  10436. },
  10437. enumerable: true,
  10438. configurable: true
  10439. });
  10440. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10441. if (this._blendConstants[0] === r &&
  10442. this._blendConstants[1] === g &&
  10443. this._blendConstants[2] === b &&
  10444. this._blendConstants[3] === a) {
  10445. return;
  10446. }
  10447. this._blendConstants[0] = r;
  10448. this._blendConstants[1] = g;
  10449. this._blendConstants[2] = b;
  10450. this._blendConstants[3] = a;
  10451. this._isBlendConstantsDirty = true;
  10452. };
  10453. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10454. if (this._blendFunctionParameters[0] === value0 &&
  10455. this._blendFunctionParameters[1] === value1 &&
  10456. this._blendFunctionParameters[2] === value2 &&
  10457. this._blendFunctionParameters[3] === value3) {
  10458. return;
  10459. }
  10460. this._blendFunctionParameters[0] = value0;
  10461. this._blendFunctionParameters[1] = value1;
  10462. this._blendFunctionParameters[2] = value2;
  10463. this._blendFunctionParameters[3] = value3;
  10464. this._isBlendFunctionParametersDirty = true;
  10465. };
  10466. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10467. if (this._blendEquationParameters[0] === rgb &&
  10468. this._blendEquationParameters[1] === alpha) {
  10469. return;
  10470. }
  10471. this._blendEquationParameters[0] = rgb;
  10472. this._blendEquationParameters[1] = alpha;
  10473. this._isBlendEquationParametersDirty = true;
  10474. };
  10475. _AlphaState.prototype.reset = function () {
  10476. this._alphaBlend = false;
  10477. this._blendFunctionParameters[0] = null;
  10478. this._blendFunctionParameters[1] = null;
  10479. this._blendFunctionParameters[2] = null;
  10480. this._blendFunctionParameters[3] = null;
  10481. this._blendEquationParameters[0] = null;
  10482. this._blendEquationParameters[1] = null;
  10483. this._blendConstants[0] = null;
  10484. this._blendConstants[1] = null;
  10485. this._blendConstants[2] = null;
  10486. this._blendConstants[3] = null;
  10487. this._isAlphaBlendDirty = true;
  10488. this._isBlendFunctionParametersDirty = false;
  10489. this._isBlendEquationParametersDirty = false;
  10490. this._isBlendConstantsDirty = false;
  10491. };
  10492. _AlphaState.prototype.apply = function (gl) {
  10493. if (!this.isDirty) {
  10494. return;
  10495. }
  10496. // Alpha blend
  10497. if (this._isAlphaBlendDirty) {
  10498. if (this._alphaBlend) {
  10499. gl.enable(gl.BLEND);
  10500. }
  10501. else {
  10502. gl.disable(gl.BLEND);
  10503. }
  10504. this._isAlphaBlendDirty = false;
  10505. }
  10506. // Alpha function
  10507. if (this._isBlendFunctionParametersDirty) {
  10508. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10509. this._isBlendFunctionParametersDirty = false;
  10510. }
  10511. // Alpha equation
  10512. if (this._isBlendEquationParametersDirty) {
  10513. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10514. this._isBlendEquationParametersDirty = false;
  10515. }
  10516. // Constants
  10517. if (this._isBlendConstantsDirty) {
  10518. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10519. this._isBlendConstantsDirty = false;
  10520. }
  10521. };
  10522. return _AlphaState;
  10523. }());
  10524. BABYLON._AlphaState = _AlphaState;
  10525. })(BABYLON || (BABYLON = {}));
  10526. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10527. var BABYLON;
  10528. (function (BABYLON) {
  10529. /**
  10530. * @hidden
  10531. **/
  10532. var _DepthCullingState = /** @class */ (function () {
  10533. /**
  10534. * Initializes the state.
  10535. */
  10536. function _DepthCullingState() {
  10537. this._isDepthTestDirty = false;
  10538. this._isDepthMaskDirty = false;
  10539. this._isDepthFuncDirty = false;
  10540. this._isCullFaceDirty = false;
  10541. this._isCullDirty = false;
  10542. this._isZOffsetDirty = false;
  10543. this._isFrontFaceDirty = false;
  10544. this.reset();
  10545. }
  10546. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10547. get: function () {
  10548. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10549. },
  10550. enumerable: true,
  10551. configurable: true
  10552. });
  10553. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10554. get: function () {
  10555. return this._zOffset;
  10556. },
  10557. set: function (value) {
  10558. if (this._zOffset === value) {
  10559. return;
  10560. }
  10561. this._zOffset = value;
  10562. this._isZOffsetDirty = true;
  10563. },
  10564. enumerable: true,
  10565. configurable: true
  10566. });
  10567. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10568. get: function () {
  10569. return this._cullFace;
  10570. },
  10571. set: function (value) {
  10572. if (this._cullFace === value) {
  10573. return;
  10574. }
  10575. this._cullFace = value;
  10576. this._isCullFaceDirty = true;
  10577. },
  10578. enumerable: true,
  10579. configurable: true
  10580. });
  10581. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10582. get: function () {
  10583. return this._cull;
  10584. },
  10585. set: function (value) {
  10586. if (this._cull === value) {
  10587. return;
  10588. }
  10589. this._cull = value;
  10590. this._isCullDirty = true;
  10591. },
  10592. enumerable: true,
  10593. configurable: true
  10594. });
  10595. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10596. get: function () {
  10597. return this._depthFunc;
  10598. },
  10599. set: function (value) {
  10600. if (this._depthFunc === value) {
  10601. return;
  10602. }
  10603. this._depthFunc = value;
  10604. this._isDepthFuncDirty = true;
  10605. },
  10606. enumerable: true,
  10607. configurable: true
  10608. });
  10609. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10610. get: function () {
  10611. return this._depthMask;
  10612. },
  10613. set: function (value) {
  10614. if (this._depthMask === value) {
  10615. return;
  10616. }
  10617. this._depthMask = value;
  10618. this._isDepthMaskDirty = true;
  10619. },
  10620. enumerable: true,
  10621. configurable: true
  10622. });
  10623. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10624. get: function () {
  10625. return this._depthTest;
  10626. },
  10627. set: function (value) {
  10628. if (this._depthTest === value) {
  10629. return;
  10630. }
  10631. this._depthTest = value;
  10632. this._isDepthTestDirty = true;
  10633. },
  10634. enumerable: true,
  10635. configurable: true
  10636. });
  10637. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10638. get: function () {
  10639. return this._frontFace;
  10640. },
  10641. set: function (value) {
  10642. if (this._frontFace === value) {
  10643. return;
  10644. }
  10645. this._frontFace = value;
  10646. this._isFrontFaceDirty = true;
  10647. },
  10648. enumerable: true,
  10649. configurable: true
  10650. });
  10651. _DepthCullingState.prototype.reset = function () {
  10652. this._depthMask = true;
  10653. this._depthTest = true;
  10654. this._depthFunc = null;
  10655. this._cullFace = null;
  10656. this._cull = null;
  10657. this._zOffset = 0;
  10658. this._frontFace = null;
  10659. this._isDepthTestDirty = true;
  10660. this._isDepthMaskDirty = true;
  10661. this._isDepthFuncDirty = false;
  10662. this._isCullFaceDirty = false;
  10663. this._isCullDirty = false;
  10664. this._isZOffsetDirty = false;
  10665. this._isFrontFaceDirty = false;
  10666. };
  10667. _DepthCullingState.prototype.apply = function (gl) {
  10668. if (!this.isDirty) {
  10669. return;
  10670. }
  10671. // Cull
  10672. if (this._isCullDirty) {
  10673. if (this.cull) {
  10674. gl.enable(gl.CULL_FACE);
  10675. }
  10676. else {
  10677. gl.disable(gl.CULL_FACE);
  10678. }
  10679. this._isCullDirty = false;
  10680. }
  10681. // Cull face
  10682. if (this._isCullFaceDirty) {
  10683. gl.cullFace(this.cullFace);
  10684. this._isCullFaceDirty = false;
  10685. }
  10686. // Depth mask
  10687. if (this._isDepthMaskDirty) {
  10688. gl.depthMask(this.depthMask);
  10689. this._isDepthMaskDirty = false;
  10690. }
  10691. // Depth test
  10692. if (this._isDepthTestDirty) {
  10693. if (this.depthTest) {
  10694. gl.enable(gl.DEPTH_TEST);
  10695. }
  10696. else {
  10697. gl.disable(gl.DEPTH_TEST);
  10698. }
  10699. this._isDepthTestDirty = false;
  10700. }
  10701. // Depth func
  10702. if (this._isDepthFuncDirty) {
  10703. gl.depthFunc(this.depthFunc);
  10704. this._isDepthFuncDirty = false;
  10705. }
  10706. // zOffset
  10707. if (this._isZOffsetDirty) {
  10708. if (this.zOffset) {
  10709. gl.enable(gl.POLYGON_OFFSET_FILL);
  10710. gl.polygonOffset(this.zOffset, 0);
  10711. }
  10712. else {
  10713. gl.disable(gl.POLYGON_OFFSET_FILL);
  10714. }
  10715. this._isZOffsetDirty = false;
  10716. }
  10717. // Front face
  10718. if (this._isFrontFaceDirty) {
  10719. gl.frontFace(this.frontFace);
  10720. this._isFrontFaceDirty = false;
  10721. }
  10722. };
  10723. return _DepthCullingState;
  10724. }());
  10725. BABYLON._DepthCullingState = _DepthCullingState;
  10726. })(BABYLON || (BABYLON = {}));
  10727. //# sourceMappingURL=babylon.depthCullingState.js.map
  10728. var BABYLON;
  10729. (function (BABYLON) {
  10730. /**
  10731. * @hidden
  10732. **/
  10733. var _StencilState = /** @class */ (function () {
  10734. function _StencilState() {
  10735. this._isStencilTestDirty = false;
  10736. this._isStencilMaskDirty = false;
  10737. this._isStencilFuncDirty = false;
  10738. this._isStencilOpDirty = false;
  10739. this.reset();
  10740. }
  10741. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10742. get: function () {
  10743. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10749. get: function () {
  10750. return this._stencilFunc;
  10751. },
  10752. set: function (value) {
  10753. if (this._stencilFunc === value) {
  10754. return;
  10755. }
  10756. this._stencilFunc = value;
  10757. this._isStencilFuncDirty = true;
  10758. },
  10759. enumerable: true,
  10760. configurable: true
  10761. });
  10762. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10763. get: function () {
  10764. return this._stencilFuncRef;
  10765. },
  10766. set: function (value) {
  10767. if (this._stencilFuncRef === value) {
  10768. return;
  10769. }
  10770. this._stencilFuncRef = value;
  10771. this._isStencilFuncDirty = true;
  10772. },
  10773. enumerable: true,
  10774. configurable: true
  10775. });
  10776. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10777. get: function () {
  10778. return this._stencilFuncMask;
  10779. },
  10780. set: function (value) {
  10781. if (this._stencilFuncMask === value) {
  10782. return;
  10783. }
  10784. this._stencilFuncMask = value;
  10785. this._isStencilFuncDirty = true;
  10786. },
  10787. enumerable: true,
  10788. configurable: true
  10789. });
  10790. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10791. get: function () {
  10792. return this._stencilOpStencilFail;
  10793. },
  10794. set: function (value) {
  10795. if (this._stencilOpStencilFail === value) {
  10796. return;
  10797. }
  10798. this._stencilOpStencilFail = value;
  10799. this._isStencilOpDirty = true;
  10800. },
  10801. enumerable: true,
  10802. configurable: true
  10803. });
  10804. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10805. get: function () {
  10806. return this._stencilOpDepthFail;
  10807. },
  10808. set: function (value) {
  10809. if (this._stencilOpDepthFail === value) {
  10810. return;
  10811. }
  10812. this._stencilOpDepthFail = value;
  10813. this._isStencilOpDirty = true;
  10814. },
  10815. enumerable: true,
  10816. configurable: true
  10817. });
  10818. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10819. get: function () {
  10820. return this._stencilOpStencilDepthPass;
  10821. },
  10822. set: function (value) {
  10823. if (this._stencilOpStencilDepthPass === value) {
  10824. return;
  10825. }
  10826. this._stencilOpStencilDepthPass = value;
  10827. this._isStencilOpDirty = true;
  10828. },
  10829. enumerable: true,
  10830. configurable: true
  10831. });
  10832. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10833. get: function () {
  10834. return this._stencilMask;
  10835. },
  10836. set: function (value) {
  10837. if (this._stencilMask === value) {
  10838. return;
  10839. }
  10840. this._stencilMask = value;
  10841. this._isStencilMaskDirty = true;
  10842. },
  10843. enumerable: true,
  10844. configurable: true
  10845. });
  10846. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10847. get: function () {
  10848. return this._stencilTest;
  10849. },
  10850. set: function (value) {
  10851. if (this._stencilTest === value) {
  10852. return;
  10853. }
  10854. this._stencilTest = value;
  10855. this._isStencilTestDirty = true;
  10856. },
  10857. enumerable: true,
  10858. configurable: true
  10859. });
  10860. _StencilState.prototype.reset = function () {
  10861. this._stencilTest = false;
  10862. this._stencilMask = 0xFF;
  10863. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10864. this._stencilFuncRef = 1;
  10865. this._stencilFuncMask = 0xFF;
  10866. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10867. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10868. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10869. this._isStencilTestDirty = true;
  10870. this._isStencilMaskDirty = true;
  10871. this._isStencilFuncDirty = true;
  10872. this._isStencilOpDirty = true;
  10873. };
  10874. _StencilState.prototype.apply = function (gl) {
  10875. if (!this.isDirty) {
  10876. return;
  10877. }
  10878. // Stencil test
  10879. if (this._isStencilTestDirty) {
  10880. if (this.stencilTest) {
  10881. gl.enable(gl.STENCIL_TEST);
  10882. }
  10883. else {
  10884. gl.disable(gl.STENCIL_TEST);
  10885. }
  10886. this._isStencilTestDirty = false;
  10887. }
  10888. // Stencil mask
  10889. if (this._isStencilMaskDirty) {
  10890. gl.stencilMask(this.stencilMask);
  10891. this._isStencilMaskDirty = false;
  10892. }
  10893. // Stencil func
  10894. if (this._isStencilFuncDirty) {
  10895. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10896. this._isStencilFuncDirty = false;
  10897. }
  10898. // Stencil op
  10899. if (this._isStencilOpDirty) {
  10900. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10901. this._isStencilOpDirty = false;
  10902. }
  10903. };
  10904. return _StencilState;
  10905. }());
  10906. BABYLON._StencilState = _StencilState;
  10907. })(BABYLON || (BABYLON = {}));
  10908. //# sourceMappingURL=babylon.stencilState.js.map
  10909. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10910. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10911. s = arguments[i];
  10912. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10913. t[p] = s[p];
  10914. }
  10915. return t;
  10916. };
  10917. var BABYLON;
  10918. (function (BABYLON) {
  10919. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10920. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10921. };
  10922. var compileRawShader = function (gl, source, type) {
  10923. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10924. gl.shaderSource(shader, source);
  10925. gl.compileShader(shader);
  10926. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10927. var log = gl.getShaderInfoLog(shader);
  10928. if (log) {
  10929. throw new Error(log);
  10930. }
  10931. }
  10932. if (!shader) {
  10933. throw new Error("Something went wrong while compile the shader.");
  10934. }
  10935. return shader;
  10936. };
  10937. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10938. var magFilter = gl.NEAREST;
  10939. var minFilter = gl.NEAREST;
  10940. switch (samplingMode) {
  10941. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10942. magFilter = gl.LINEAR;
  10943. if (generateMipMaps) {
  10944. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10945. }
  10946. else {
  10947. minFilter = gl.LINEAR;
  10948. }
  10949. break;
  10950. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10951. magFilter = gl.LINEAR;
  10952. if (generateMipMaps) {
  10953. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10954. }
  10955. else {
  10956. minFilter = gl.LINEAR;
  10957. }
  10958. break;
  10959. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10960. magFilter = gl.NEAREST;
  10961. if (generateMipMaps) {
  10962. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10963. }
  10964. else {
  10965. minFilter = gl.NEAREST;
  10966. }
  10967. break;
  10968. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10969. magFilter = gl.NEAREST;
  10970. if (generateMipMaps) {
  10971. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10972. }
  10973. else {
  10974. minFilter = gl.NEAREST;
  10975. }
  10976. break;
  10977. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10978. magFilter = gl.NEAREST;
  10979. if (generateMipMaps) {
  10980. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10981. }
  10982. else {
  10983. minFilter = gl.LINEAR;
  10984. }
  10985. break;
  10986. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10987. magFilter = gl.NEAREST;
  10988. if (generateMipMaps) {
  10989. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10990. }
  10991. else {
  10992. minFilter = gl.LINEAR;
  10993. }
  10994. break;
  10995. case BABYLON.Texture.NEAREST_LINEAR:
  10996. magFilter = gl.NEAREST;
  10997. minFilter = gl.LINEAR;
  10998. break;
  10999. case BABYLON.Texture.NEAREST_NEAREST:
  11000. magFilter = gl.NEAREST;
  11001. minFilter = gl.NEAREST;
  11002. break;
  11003. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11004. magFilter = gl.LINEAR;
  11005. if (generateMipMaps) {
  11006. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11007. }
  11008. else {
  11009. minFilter = gl.NEAREST;
  11010. }
  11011. break;
  11012. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11013. magFilter = gl.LINEAR;
  11014. if (generateMipMaps) {
  11015. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11016. }
  11017. else {
  11018. minFilter = gl.NEAREST;
  11019. }
  11020. break;
  11021. case BABYLON.Texture.LINEAR_LINEAR:
  11022. magFilter = gl.LINEAR;
  11023. minFilter = gl.LINEAR;
  11024. break;
  11025. case BABYLON.Texture.LINEAR_NEAREST:
  11026. magFilter = gl.LINEAR;
  11027. minFilter = gl.NEAREST;
  11028. break;
  11029. }
  11030. return {
  11031. min: minFilter,
  11032. mag: magFilter
  11033. };
  11034. };
  11035. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11036. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11037. var img;
  11038. var onload = function () {
  11039. loadedImages[index] = img;
  11040. loadedImages._internalCount++;
  11041. if (scene) {
  11042. scene._removePendingData(img);
  11043. }
  11044. if (loadedImages._internalCount === 6) {
  11045. onfinish(loadedImages);
  11046. }
  11047. };
  11048. var onerror = function (message, exception) {
  11049. if (scene) {
  11050. scene._removePendingData(img);
  11051. }
  11052. if (onErrorCallBack) {
  11053. onErrorCallBack(message, exception);
  11054. }
  11055. };
  11056. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11057. if (scene) {
  11058. scene._addPendingData(img);
  11059. }
  11060. };
  11061. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11062. if (onError === void 0) { onError = null; }
  11063. var loadedImages = [];
  11064. loadedImages._internalCount = 0;
  11065. for (var index = 0; index < 6; index++) {
  11066. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11067. }
  11068. };
  11069. var BufferPointer = /** @class */ (function () {
  11070. function BufferPointer() {
  11071. }
  11072. return BufferPointer;
  11073. }());
  11074. /**
  11075. * Interface for attribute information associated with buffer instanciation
  11076. */
  11077. var InstancingAttributeInfo = /** @class */ (function () {
  11078. function InstancingAttributeInfo() {
  11079. }
  11080. return InstancingAttributeInfo;
  11081. }());
  11082. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11083. /**
  11084. * Define options used to create a render target texture
  11085. */
  11086. var RenderTargetCreationOptions = /** @class */ (function () {
  11087. function RenderTargetCreationOptions() {
  11088. }
  11089. return RenderTargetCreationOptions;
  11090. }());
  11091. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11092. /**
  11093. * Define options used to create a depth texture
  11094. */
  11095. var DepthTextureCreationOptions = /** @class */ (function () {
  11096. function DepthTextureCreationOptions() {
  11097. }
  11098. return DepthTextureCreationOptions;
  11099. }());
  11100. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11101. /**
  11102. * Class used to describe the capabilities of the engine relatively to the current browser
  11103. */
  11104. var EngineCapabilities = /** @class */ (function () {
  11105. function EngineCapabilities() {
  11106. }
  11107. return EngineCapabilities;
  11108. }());
  11109. BABYLON.EngineCapabilities = EngineCapabilities;
  11110. /**
  11111. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11112. */
  11113. var Engine = /** @class */ (function () {
  11114. /**
  11115. * Creates a new engine
  11116. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11117. * @param antialias defines enable antialiasing (default: false)
  11118. * @param options defines further options to be sent to the getContext() function
  11119. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11120. */
  11121. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11122. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11123. var _this = this;
  11124. // Public members
  11125. /**
  11126. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11127. */
  11128. this.forcePOTTextures = false;
  11129. /**
  11130. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11131. */
  11132. this.isFullscreen = false;
  11133. /**
  11134. * Gets a boolean indicating if the pointer is currently locked
  11135. */
  11136. this.isPointerLock = false;
  11137. /**
  11138. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11139. */
  11140. this.cullBackFaces = true;
  11141. /**
  11142. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11143. */
  11144. this.renderEvenInBackground = true;
  11145. /**
  11146. * Gets or sets a boolean indicating that cache can be kept between frames
  11147. */
  11148. this.preventCacheWipeBetweenFrames = false;
  11149. /**
  11150. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11151. **/
  11152. this.enableOfflineSupport = false;
  11153. /**
  11154. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11155. **/
  11156. this.disableManifestCheck = false;
  11157. /**
  11158. * Gets the list of created scenes
  11159. */
  11160. this.scenes = new Array();
  11161. /**
  11162. * Gets the list of created postprocesses
  11163. */
  11164. this.postProcesses = new Array();
  11165. // Observables
  11166. /**
  11167. * Observable event triggered each time the rendering canvas is resized
  11168. */
  11169. this.onResizeObservable = new BABYLON.Observable();
  11170. /**
  11171. * Observable event triggered each time the canvas loses focus
  11172. */
  11173. this.onCanvasBlurObservable = new BABYLON.Observable();
  11174. /**
  11175. * Observable event triggered each time the canvas gains focus
  11176. */
  11177. this.onCanvasFocusObservable = new BABYLON.Observable();
  11178. /**
  11179. * Observable event triggered each time the canvas receives pointerout event
  11180. */
  11181. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11182. /**
  11183. * Observable event triggered before each texture is initialized
  11184. */
  11185. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11186. //WebVR
  11187. this._vrDisplay = undefined;
  11188. this._vrSupported = false;
  11189. this._vrExclusivePointerMode = false;
  11190. // Uniform buffers list
  11191. /**
  11192. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11193. */
  11194. this.disableUniformBuffers = false;
  11195. /** @hidden */
  11196. this._uniformBuffers = new Array();
  11197. // Observables
  11198. /**
  11199. * Observable raised when the engine begins a new frame
  11200. */
  11201. this.onBeginFrameObservable = new BABYLON.Observable();
  11202. /**
  11203. * Observable raised when the engine ends the current frame
  11204. */
  11205. this.onEndFrameObservable = new BABYLON.Observable();
  11206. /**
  11207. * Observable raised when the engine is about to compile a shader
  11208. */
  11209. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11210. /**
  11211. * Observable raised when the engine has jsut compiled a shader
  11212. */
  11213. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11214. this._windowIsBackground = false;
  11215. this._webGLVersion = 1.0;
  11216. /** @hidden */
  11217. this._badOS = false;
  11218. /** @hidden */
  11219. this._badDesktopOS = false;
  11220. /**
  11221. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11222. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11223. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11224. */
  11225. this.disableTextureBindingOptimization = false;
  11226. /**
  11227. * Observable signaled when VR display mode changes
  11228. */
  11229. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11230. /**
  11231. * Observable signaled when VR request present is complete
  11232. */
  11233. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11234. /**
  11235. * Observable signaled when VR request present starts
  11236. */
  11237. this.onVRRequestPresentStart = new BABYLON.Observable();
  11238. this._colorWrite = true;
  11239. /** @hidden */
  11240. this._drawCalls = new BABYLON.PerfCounter();
  11241. /** @hidden */
  11242. this._textureCollisions = new BABYLON.PerfCounter();
  11243. this._renderingQueueLaunched = false;
  11244. this._activeRenderLoops = new Array();
  11245. // Deterministic lockstepMaxSteps
  11246. this._deterministicLockstep = false;
  11247. this._lockstepMaxSteps = 4;
  11248. // Lost context
  11249. /**
  11250. * Observable signaled when a context lost event is raised
  11251. */
  11252. this.onContextLostObservable = new BABYLON.Observable();
  11253. /**
  11254. * Observable signaled when a context restored event is raised
  11255. */
  11256. this.onContextRestoredObservable = new BABYLON.Observable();
  11257. this._contextWasLost = false;
  11258. this._doNotHandleContextLost = false;
  11259. // FPS
  11260. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11261. this._fps = 60;
  11262. this._deltaTime = 0;
  11263. /**
  11264. * Turn this value on if you want to pause FPS computation when in background
  11265. */
  11266. this.disablePerformanceMonitorInBackground = false;
  11267. // States
  11268. /** @hidden */
  11269. this._depthCullingState = new BABYLON._DepthCullingState();
  11270. /** @hidden */
  11271. this._stencilState = new BABYLON._StencilState();
  11272. /** @hidden */
  11273. this._alphaState = new BABYLON._AlphaState();
  11274. /** @hidden */
  11275. this._alphaMode = Engine.ALPHA_DISABLE;
  11276. // Cache
  11277. this._internalTexturesCache = new Array();
  11278. /** @hidden */
  11279. this._activeChannel = 0;
  11280. this._currentTextureChannel = -1;
  11281. /** @hidden */
  11282. this._boundTexturesCache = {};
  11283. this._compiledEffects = {};
  11284. this._vertexAttribArraysEnabled = [];
  11285. this._uintIndicesCurrentlySet = false;
  11286. this._currentBoundBuffer = new Array();
  11287. this._currentBufferPointers = new Array();
  11288. this._currentInstanceLocations = new Array();
  11289. this._currentInstanceBuffers = new Array();
  11290. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11291. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11292. this._vaoRecordInProgress = false;
  11293. this._mustWipeVertexAttributes = false;
  11294. this._nextFreeTextureSlots = new Array();
  11295. this._maxSimultaneousTextures = 0;
  11296. this._activeRequests = new Array();
  11297. // Hardware supported Compressed Textures
  11298. this._texturesSupported = new Array();
  11299. this._onVRFullScreenTriggered = function () {
  11300. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11301. //get the old size before we change
  11302. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11303. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11304. //get the width and height, change the render size
  11305. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11306. _this.setHardwareScalingLevel(1);
  11307. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11308. }
  11309. else {
  11310. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11311. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11312. }
  11313. };
  11314. this._boundUniforms = {};
  11315. // Register promises
  11316. BABYLON.PromisePolyfill.Apply();
  11317. var canvas = null;
  11318. Engine.Instances.push(this);
  11319. if (!canvasOrContext) {
  11320. return;
  11321. }
  11322. options = options || {};
  11323. if (canvasOrContext.getContext) {
  11324. canvas = canvasOrContext;
  11325. this._renderingCanvas = canvas;
  11326. if (antialias != null) {
  11327. options.antialias = antialias;
  11328. }
  11329. if (options.deterministicLockstep === undefined) {
  11330. options.deterministicLockstep = false;
  11331. }
  11332. if (options.lockstepMaxSteps === undefined) {
  11333. options.lockstepMaxSteps = 4;
  11334. }
  11335. if (options.preserveDrawingBuffer === undefined) {
  11336. options.preserveDrawingBuffer = false;
  11337. }
  11338. if (options.audioEngine === undefined) {
  11339. options.audioEngine = true;
  11340. }
  11341. if (options.stencil === undefined) {
  11342. options.stencil = true;
  11343. }
  11344. this._deterministicLockstep = options.deterministicLockstep;
  11345. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11346. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11347. // Exceptions
  11348. if (navigator && navigator.userAgent) {
  11349. var ua = navigator.userAgent;
  11350. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11351. var exception = _a[_i];
  11352. var key = exception.key;
  11353. var targets = exception.targets;
  11354. if (ua.indexOf(key) > -1) {
  11355. if (exception.capture && exception.captureConstraint) {
  11356. var capture = exception.capture;
  11357. var constraint = exception.captureConstraint;
  11358. var regex = new RegExp(capture);
  11359. var matches = regex.exec(ua);
  11360. if (matches && matches.length > 0) {
  11361. var capturedValue = parseInt(matches[matches.length - 1]);
  11362. if (capturedValue >= constraint) {
  11363. continue;
  11364. }
  11365. }
  11366. }
  11367. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11368. var target = targets_1[_b];
  11369. switch (target) {
  11370. case "uniformBuffer":
  11371. this.disableUniformBuffers = true;
  11372. break;
  11373. case "textureBindingOptimization":
  11374. this.disableTextureBindingOptimization = true;
  11375. break;
  11376. }
  11377. }
  11378. }
  11379. }
  11380. }
  11381. // GL
  11382. if (!options.disableWebGL2Support) {
  11383. try {
  11384. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11385. if (this._gl) {
  11386. this._webGLVersion = 2.0;
  11387. }
  11388. }
  11389. catch (e) {
  11390. // Do nothing
  11391. }
  11392. }
  11393. if (!this._gl) {
  11394. if (!canvas) {
  11395. throw new Error("The provided canvas is null or undefined.");
  11396. }
  11397. try {
  11398. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11399. }
  11400. catch (e) {
  11401. throw new Error("WebGL not supported");
  11402. }
  11403. }
  11404. if (!this._gl) {
  11405. throw new Error("WebGL not supported");
  11406. }
  11407. this._onCanvasFocus = function () {
  11408. _this.onCanvasFocusObservable.notifyObservers(_this);
  11409. };
  11410. this._onCanvasBlur = function () {
  11411. _this.onCanvasBlurObservable.notifyObservers(_this);
  11412. };
  11413. canvas.addEventListener("focus", this._onCanvasFocus);
  11414. canvas.addEventListener("blur", this._onCanvasBlur);
  11415. this._onBlur = function () {
  11416. if (_this.disablePerformanceMonitorInBackground) {
  11417. _this._performanceMonitor.disable();
  11418. }
  11419. _this._windowIsBackground = true;
  11420. };
  11421. this._onFocus = function () {
  11422. if (_this.disablePerformanceMonitorInBackground) {
  11423. _this._performanceMonitor.enable();
  11424. }
  11425. _this._windowIsBackground = false;
  11426. };
  11427. this._onCanvasPointerOut = function (ev) {
  11428. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11429. };
  11430. window.addEventListener("blur", this._onBlur);
  11431. window.addEventListener("focus", this._onFocus);
  11432. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11433. // Context lost
  11434. if (!this._doNotHandleContextLost) {
  11435. this._onContextLost = function (evt) {
  11436. evt.preventDefault();
  11437. _this._contextWasLost = true;
  11438. BABYLON.Tools.Warn("WebGL context lost.");
  11439. _this.onContextLostObservable.notifyObservers(_this);
  11440. };
  11441. this._onContextRestored = function (evt) {
  11442. // Adding a timeout to avoid race condition at browser level
  11443. setTimeout(function () {
  11444. // Rebuild gl context
  11445. _this._initGLContext();
  11446. // Rebuild effects
  11447. _this._rebuildEffects();
  11448. // Rebuild textures
  11449. _this._rebuildInternalTextures();
  11450. // Rebuild buffers
  11451. _this._rebuildBuffers();
  11452. // Cache
  11453. _this.wipeCaches(true);
  11454. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11455. _this.onContextRestoredObservable.notifyObservers(_this);
  11456. _this._contextWasLost = false;
  11457. }, 0);
  11458. };
  11459. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11460. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11461. }
  11462. }
  11463. else {
  11464. this._gl = canvasOrContext;
  11465. this._renderingCanvas = this._gl.canvas;
  11466. if (this._gl.renderbufferStorageMultisample) {
  11467. this._webGLVersion = 2.0;
  11468. }
  11469. options.stencil = this._gl.getContextAttributes().stencil;
  11470. }
  11471. // Viewport
  11472. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11473. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11474. this.resize();
  11475. this._isStencilEnable = options.stencil ? true : false;
  11476. this._initGLContext();
  11477. if (canvas) {
  11478. // Fullscreen
  11479. this._onFullscreenChange = function () {
  11480. if (document.fullscreen !== undefined) {
  11481. _this.isFullscreen = document.fullscreen;
  11482. }
  11483. else if (document.mozFullScreen !== undefined) {
  11484. _this.isFullscreen = document.mozFullScreen;
  11485. }
  11486. else if (document.webkitIsFullScreen !== undefined) {
  11487. _this.isFullscreen = document.webkitIsFullScreen;
  11488. }
  11489. else if (document.msIsFullScreen !== undefined) {
  11490. _this.isFullscreen = document.msIsFullScreen;
  11491. }
  11492. // Pointer lock
  11493. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11494. canvas.requestPointerLock = canvas.requestPointerLock ||
  11495. canvas.msRequestPointerLock ||
  11496. canvas.mozRequestPointerLock ||
  11497. canvas.webkitRequestPointerLock;
  11498. if (canvas.requestPointerLock) {
  11499. canvas.requestPointerLock();
  11500. }
  11501. }
  11502. };
  11503. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11504. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11505. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11506. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11507. // Pointer lock
  11508. this._onPointerLockChange = function () {
  11509. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11510. document.webkitPointerLockElement === canvas ||
  11511. document.msPointerLockElement === canvas ||
  11512. document.pointerLockElement === canvas);
  11513. };
  11514. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11515. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11516. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11517. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11518. this._onVRDisplayPointerRestricted = function () {
  11519. if (canvas) {
  11520. canvas.requestPointerLock();
  11521. }
  11522. };
  11523. this._onVRDisplayPointerUnrestricted = function () {
  11524. document.exitPointerLock();
  11525. };
  11526. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11527. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11528. }
  11529. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11530. Engine.audioEngine = new BABYLON.AudioEngine();
  11531. }
  11532. // Prepare buffer pointers
  11533. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11534. this._currentBufferPointers[i] = new BufferPointer();
  11535. }
  11536. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11537. // Load WebVR Devices
  11538. if (options.autoEnableWebVR) {
  11539. this.initWebVR();
  11540. }
  11541. // Detect if we are running on a faulty buggy OS.
  11542. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11543. // Detect if we are running on a faulty buggy desktop OS.
  11544. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11545. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11546. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11547. }
  11548. Object.defineProperty(Engine, "LastCreatedEngine", {
  11549. /**
  11550. * Gets the latest created engine
  11551. */
  11552. get: function () {
  11553. if (Engine.Instances.length === 0) {
  11554. return null;
  11555. }
  11556. return Engine.Instances[Engine.Instances.length - 1];
  11557. },
  11558. enumerable: true,
  11559. configurable: true
  11560. });
  11561. Object.defineProperty(Engine, "LastCreatedScene", {
  11562. /**
  11563. * Gets the latest created scene
  11564. */
  11565. get: function () {
  11566. var lastCreatedEngine = Engine.LastCreatedEngine;
  11567. if (!lastCreatedEngine) {
  11568. return null;
  11569. }
  11570. if (lastCreatedEngine.scenes.length === 0) {
  11571. return null;
  11572. }
  11573. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11574. },
  11575. enumerable: true,
  11576. configurable: true
  11577. });
  11578. /**
  11579. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11580. * @param flag defines which part of the materials must be marked as dirty
  11581. * @param predicate defines a predicate used to filter which materials should be affected
  11582. */
  11583. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11584. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11585. var engine = Engine.Instances[engineIndex];
  11586. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11587. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11588. }
  11589. }
  11590. };
  11591. Object.defineProperty(Engine, "NEVER", {
  11592. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11593. get: function () {
  11594. return Engine._NEVER;
  11595. },
  11596. enumerable: true,
  11597. configurable: true
  11598. });
  11599. Object.defineProperty(Engine, "ALWAYS", {
  11600. /** 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 */
  11601. get: function () {
  11602. return Engine._ALWAYS;
  11603. },
  11604. enumerable: true,
  11605. configurable: true
  11606. });
  11607. Object.defineProperty(Engine, "LESS", {
  11608. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11609. get: function () {
  11610. return Engine._LESS;
  11611. },
  11612. enumerable: true,
  11613. configurable: true
  11614. });
  11615. Object.defineProperty(Engine, "EQUAL", {
  11616. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11617. get: function () {
  11618. return Engine._EQUAL;
  11619. },
  11620. enumerable: true,
  11621. configurable: true
  11622. });
  11623. Object.defineProperty(Engine, "LEQUAL", {
  11624. /** 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 */
  11625. get: function () {
  11626. return Engine._LEQUAL;
  11627. },
  11628. enumerable: true,
  11629. configurable: true
  11630. });
  11631. Object.defineProperty(Engine, "GREATER", {
  11632. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11633. get: function () {
  11634. return Engine._GREATER;
  11635. },
  11636. enumerable: true,
  11637. configurable: true
  11638. });
  11639. Object.defineProperty(Engine, "GEQUAL", {
  11640. /** 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 */
  11641. get: function () {
  11642. return Engine._GEQUAL;
  11643. },
  11644. enumerable: true,
  11645. configurable: true
  11646. });
  11647. Object.defineProperty(Engine, "NOTEQUAL", {
  11648. /** 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 */
  11649. get: function () {
  11650. return Engine._NOTEQUAL;
  11651. },
  11652. enumerable: true,
  11653. configurable: true
  11654. });
  11655. Object.defineProperty(Engine, "KEEP", {
  11656. /** Passed to stencilOperation to specify that stencil value must be kept */
  11657. get: function () {
  11658. return Engine._KEEP;
  11659. },
  11660. enumerable: true,
  11661. configurable: true
  11662. });
  11663. Object.defineProperty(Engine, "REPLACE", {
  11664. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11665. get: function () {
  11666. return Engine._REPLACE;
  11667. },
  11668. enumerable: true,
  11669. configurable: true
  11670. });
  11671. Object.defineProperty(Engine, "INCR", {
  11672. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11673. get: function () {
  11674. return Engine._INCR;
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. Object.defineProperty(Engine, "DECR", {
  11680. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11681. get: function () {
  11682. return Engine._DECR;
  11683. },
  11684. enumerable: true,
  11685. configurable: true
  11686. });
  11687. Object.defineProperty(Engine, "INVERT", {
  11688. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11689. get: function () {
  11690. return Engine._INVERT;
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(Engine, "INCR_WRAP", {
  11696. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11697. get: function () {
  11698. return Engine._INCR_WRAP;
  11699. },
  11700. enumerable: true,
  11701. configurable: true
  11702. });
  11703. Object.defineProperty(Engine, "DECR_WRAP", {
  11704. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11705. get: function () {
  11706. return Engine._DECR_WRAP;
  11707. },
  11708. enumerable: true,
  11709. configurable: true
  11710. });
  11711. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11712. // Alpha
  11713. /** Defines that alpha blending is disabled */
  11714. get: function () {
  11715. return Engine._ALPHA_DISABLE;
  11716. },
  11717. enumerable: true,
  11718. configurable: true
  11719. });
  11720. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11721. /** Defines that alpha blending to SRC + DEST */
  11722. get: function () {
  11723. return Engine._ALPHA_ONEONE;
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(Engine, "ALPHA_ADD", {
  11729. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11730. get: function () {
  11731. return Engine._ALPHA_ADD;
  11732. },
  11733. enumerable: true,
  11734. configurable: true
  11735. });
  11736. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11737. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11738. get: function () {
  11739. return Engine._ALPHA_COMBINE;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11745. /** Defines that alpha blending to DEST - SRC * DEST */
  11746. get: function () {
  11747. return Engine._ALPHA_SUBTRACT;
  11748. },
  11749. enumerable: true,
  11750. configurable: true
  11751. });
  11752. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11753. /** Defines that alpha blending to SRC * DEST */
  11754. get: function () {
  11755. return Engine._ALPHA_MULTIPLY;
  11756. },
  11757. enumerable: true,
  11758. configurable: true
  11759. });
  11760. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11761. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11762. get: function () {
  11763. return Engine._ALPHA_MAXIMIZED;
  11764. },
  11765. enumerable: true,
  11766. configurable: true
  11767. });
  11768. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11769. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11770. get: function () {
  11771. return Engine._ALPHA_PREMULTIPLIED;
  11772. },
  11773. enumerable: true,
  11774. configurable: true
  11775. });
  11776. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11777. /**
  11778. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11779. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11780. */
  11781. get: function () {
  11782. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11788. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11789. get: function () {
  11790. return Engine._ALPHA_INTERPOLATE;
  11791. },
  11792. enumerable: true,
  11793. configurable: true
  11794. });
  11795. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11796. /**
  11797. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11798. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11799. */
  11800. get: function () {
  11801. return Engine._ALPHA_SCREENMODE;
  11802. },
  11803. enumerable: true,
  11804. configurable: true
  11805. });
  11806. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11807. // Delays
  11808. /** Defines that the ressource is not delayed*/
  11809. get: function () {
  11810. return Engine._DELAYLOADSTATE_NONE;
  11811. },
  11812. enumerable: true,
  11813. configurable: true
  11814. });
  11815. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11816. /** Defines that the ressource was successfully delay loaded */
  11817. get: function () {
  11818. return Engine._DELAYLOADSTATE_LOADED;
  11819. },
  11820. enumerable: true,
  11821. configurable: true
  11822. });
  11823. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11824. /** Defines that the ressource is currently delay loading */
  11825. get: function () {
  11826. return Engine._DELAYLOADSTATE_LOADING;
  11827. },
  11828. enumerable: true,
  11829. configurable: true
  11830. });
  11831. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11832. /** Defines that the ressource is delayed and has not started loading */
  11833. get: function () {
  11834. return Engine._DELAYLOADSTATE_NOTLOADED;
  11835. },
  11836. enumerable: true,
  11837. configurable: true
  11838. });
  11839. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11840. /** ALPHA */
  11841. get: function () {
  11842. return Engine._TEXTUREFORMAT_ALPHA;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11848. /** LUMINANCE */
  11849. get: function () {
  11850. return Engine._TEXTUREFORMAT_LUMINANCE;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11856. /**
  11857. * R32F
  11858. */
  11859. get: function () {
  11860. return Engine._TEXTUREFORMAT_R32F;
  11861. },
  11862. enumerable: true,
  11863. configurable: true
  11864. });
  11865. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11866. /**
  11867. * RG32F
  11868. */
  11869. get: function () {
  11870. return Engine._TEXTUREFORMAT_RG32F;
  11871. },
  11872. enumerable: true,
  11873. configurable: true
  11874. });
  11875. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11876. /**
  11877. * RGB32F
  11878. */
  11879. get: function () {
  11880. return Engine._TEXTUREFORMAT_RGB32F;
  11881. },
  11882. enumerable: true,
  11883. configurable: true
  11884. });
  11885. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11886. /**
  11887. * RGBA32F
  11888. */
  11889. get: function () {
  11890. return Engine._TEXTUREFORMAT_RGBA32F;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11896. /** LUMINANCE_ALPHA */
  11897. get: function () {
  11898. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11904. /** RGB */
  11905. get: function () {
  11906. return Engine._TEXTUREFORMAT_RGB;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11912. /** RGBA */
  11913. get: function () {
  11914. return Engine._TEXTUREFORMAT_RGBA;
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11920. /** UNSIGNED_INT */
  11921. get: function () {
  11922. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11923. },
  11924. enumerable: true,
  11925. configurable: true
  11926. });
  11927. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11928. /** FLOAT */
  11929. get: function () {
  11930. return Engine._TEXTURETYPE_FLOAT;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11936. /** HALF_FLOAT */
  11937. get: function () {
  11938. return Engine._TEXTURETYPE_HALF_FLOAT;
  11939. },
  11940. enumerable: true,
  11941. configurable: true
  11942. });
  11943. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11944. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11945. get: function () {
  11946. return Engine._SCALEMODE_FLOOR;
  11947. },
  11948. enumerable: true,
  11949. configurable: true
  11950. });
  11951. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11952. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11953. get: function () {
  11954. return Engine._SCALEMODE_NEAREST;
  11955. },
  11956. enumerable: true,
  11957. configurable: true
  11958. });
  11959. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11960. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11961. get: function () {
  11962. return Engine._SCALEMODE_CEILING;
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(Engine, "Version", {
  11968. /**
  11969. * Returns the current version of the framework
  11970. */
  11971. get: function () {
  11972. return "3.2.0-rc.3";
  11973. },
  11974. enumerable: true,
  11975. configurable: true
  11976. });
  11977. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11978. /**
  11979. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11980. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11981. */
  11982. get: function () {
  11983. return this._vrExclusivePointerMode;
  11984. },
  11985. enumerable: true,
  11986. configurable: true
  11987. });
  11988. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11989. /**
  11990. * Gets a boolean indicating that the engine supports uniform buffers
  11991. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11992. */
  11993. get: function () {
  11994. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11995. },
  11996. enumerable: true,
  11997. configurable: true
  11998. });
  11999. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12000. /**
  12001. * Gets a boolean indicating that only power of 2 textures are supported
  12002. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12003. */
  12004. get: function () {
  12005. return this._webGLVersion < 2 || this.forcePOTTextures;
  12006. },
  12007. enumerable: true,
  12008. configurable: true
  12009. });
  12010. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12011. /**
  12012. * Gets the performance monitor attached to this engine
  12013. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12014. */
  12015. get: function () {
  12016. return this._performanceMonitor;
  12017. },
  12018. enumerable: true,
  12019. configurable: true
  12020. });
  12021. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12022. /**
  12023. * Gets the list of texture formats supported
  12024. */
  12025. get: function () {
  12026. return this._texturesSupported;
  12027. },
  12028. enumerable: true,
  12029. configurable: true
  12030. });
  12031. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12032. /**
  12033. * Gets the list of texture formats in use
  12034. */
  12035. get: function () {
  12036. return this._textureFormatInUse;
  12037. },
  12038. enumerable: true,
  12039. configurable: true
  12040. });
  12041. Object.defineProperty(Engine.prototype, "currentViewport", {
  12042. /**
  12043. * Gets the current viewport
  12044. */
  12045. get: function () {
  12046. return this._cachedViewport;
  12047. },
  12048. enumerable: true,
  12049. configurable: true
  12050. });
  12051. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12052. /**
  12053. * Gets the default empty texture
  12054. */
  12055. get: function () {
  12056. if (!this._emptyTexture) {
  12057. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12058. }
  12059. return this._emptyTexture;
  12060. },
  12061. enumerable: true,
  12062. configurable: true
  12063. });
  12064. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12065. /**
  12066. * Gets the default empty 3D texture
  12067. */
  12068. get: function () {
  12069. if (!this._emptyTexture3D) {
  12070. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12071. }
  12072. return this._emptyTexture3D;
  12073. },
  12074. enumerable: true,
  12075. configurable: true
  12076. });
  12077. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12078. /**
  12079. * Gets the default empty cube texture
  12080. */
  12081. get: function () {
  12082. if (!this._emptyCubeTexture) {
  12083. var faceData = new Uint8Array(4);
  12084. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12085. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12086. }
  12087. return this._emptyCubeTexture;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Engine.prototype._rebuildInternalTextures = function () {
  12093. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12094. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12095. var internalTexture = currentState_1[_i];
  12096. internalTexture._rebuild();
  12097. }
  12098. };
  12099. Engine.prototype._rebuildEffects = function () {
  12100. for (var key in this._compiledEffects) {
  12101. var effect = this._compiledEffects[key];
  12102. effect._prepareEffect();
  12103. }
  12104. BABYLON.Effect.ResetCache();
  12105. };
  12106. Engine.prototype._rebuildBuffers = function () {
  12107. // Index / Vertex
  12108. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12109. var scene = _a[_i];
  12110. scene.resetCachedMaterial();
  12111. scene._rebuildGeometries();
  12112. scene._rebuildTextures();
  12113. }
  12114. // Uniforms
  12115. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12116. var uniformBuffer = _c[_b];
  12117. uniformBuffer._rebuild();
  12118. }
  12119. };
  12120. Engine.prototype._initGLContext = function () {
  12121. // Caps
  12122. this._caps = new EngineCapabilities();
  12123. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12124. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12125. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12126. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12127. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12128. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12129. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12130. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12131. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12132. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12133. // Infos
  12134. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12135. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12136. if (rendererInfo != null) {
  12137. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12138. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12139. }
  12140. if (!this._glVendor) {
  12141. this._glVendor = "Unknown vendor";
  12142. }
  12143. if (!this._glRenderer) {
  12144. this._glRenderer = "Unknown renderer";
  12145. }
  12146. // Constants
  12147. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12148. if (this._gl.RGBA16F !== 0x881A) {
  12149. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12150. }
  12151. if (this._gl.RGBA32F !== 0x8814) {
  12152. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12153. }
  12154. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12155. this._gl.DEPTH24_STENCIL8 = 35056;
  12156. }
  12157. // Extensions
  12158. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12159. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12160. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12161. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12162. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12163. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12164. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12165. 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');
  12166. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12167. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12168. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12169. this._caps.highPrecisionShaderSupported = true;
  12170. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12171. if (this._caps.timerQuery) {
  12172. if (this._webGLVersion === 1) {
  12173. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12174. }
  12175. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12176. }
  12177. // Checks if some of the format renders first to allow the use of webgl inspector.
  12178. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12179. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12180. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12181. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12182. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12183. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12184. if (this._webGLVersion > 1) {
  12185. this._gl.HALF_FLOAT_OES = 0x140B;
  12186. }
  12187. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12188. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12189. // Draw buffers
  12190. if (this._webGLVersion > 1) {
  12191. this._caps.drawBuffersExtension = true;
  12192. }
  12193. else {
  12194. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12195. if (drawBuffersExtension !== null) {
  12196. this._caps.drawBuffersExtension = true;
  12197. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12198. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12199. for (var i = 0; i < 16; i++) {
  12200. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12201. }
  12202. }
  12203. else {
  12204. this._caps.drawBuffersExtension = false;
  12205. }
  12206. }
  12207. // Depth Texture
  12208. if (this._webGLVersion > 1) {
  12209. this._caps.depthTextureExtension = true;
  12210. }
  12211. else {
  12212. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12213. if (depthTextureExtension != null) {
  12214. this._caps.depthTextureExtension = true;
  12215. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12216. }
  12217. }
  12218. // Vertex array object
  12219. if (this._webGLVersion > 1) {
  12220. this._caps.vertexArrayObject = true;
  12221. }
  12222. else {
  12223. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12224. if (vertexArrayObjectExtension != null) {
  12225. this._caps.vertexArrayObject = true;
  12226. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12227. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12228. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12229. }
  12230. else {
  12231. this._caps.vertexArrayObject = false;
  12232. }
  12233. }
  12234. // Instances count
  12235. if (this._webGLVersion > 1) {
  12236. this._caps.instancedArrays = true;
  12237. }
  12238. else {
  12239. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12240. if (instanceExtension != null) {
  12241. this._caps.instancedArrays = true;
  12242. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12243. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12244. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12245. }
  12246. else {
  12247. this._caps.instancedArrays = false;
  12248. }
  12249. }
  12250. // Intelligently add supported compressed formats in order to check for.
  12251. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12252. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12253. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12254. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12255. if (this._caps.astc)
  12256. this.texturesSupported.push('-astc.ktx');
  12257. if (this._caps.s3tc)
  12258. this.texturesSupported.push('-dxt.ktx');
  12259. if (this._caps.pvrtc)
  12260. this.texturesSupported.push('-pvrtc.ktx');
  12261. if (this._caps.etc2)
  12262. this.texturesSupported.push('-etc2.ktx');
  12263. if (this._caps.etc1)
  12264. this.texturesSupported.push('-etc1.ktx');
  12265. if (this._gl.getShaderPrecisionFormat) {
  12266. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12267. if (highp) {
  12268. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12269. }
  12270. }
  12271. // Depth buffer
  12272. this.setDepthBuffer(true);
  12273. this.setDepthFunctionToLessOrEqual();
  12274. this.setDepthWrite(true);
  12275. // Texture maps
  12276. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12277. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12278. this._nextFreeTextureSlots.push(slot);
  12279. }
  12280. };
  12281. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12282. /**
  12283. * Gets version of the current webGL context
  12284. */
  12285. get: function () {
  12286. return this._webGLVersion;
  12287. },
  12288. enumerable: true,
  12289. configurable: true
  12290. });
  12291. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12292. /**
  12293. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12294. */
  12295. get: function () {
  12296. return this._isStencilEnable;
  12297. },
  12298. enumerable: true,
  12299. configurable: true
  12300. });
  12301. Engine.prototype._prepareWorkingCanvas = function () {
  12302. if (this._workingCanvas) {
  12303. return;
  12304. }
  12305. this._workingCanvas = document.createElement("canvas");
  12306. var context = this._workingCanvas.getContext("2d");
  12307. if (context) {
  12308. this._workingContext = context;
  12309. }
  12310. };
  12311. /**
  12312. * Reset the texture cache to empty state
  12313. */
  12314. Engine.prototype.resetTextureCache = function () {
  12315. for (var key in this._boundTexturesCache) {
  12316. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12317. continue;
  12318. }
  12319. var boundTexture = this._boundTexturesCache[key];
  12320. if (boundTexture) {
  12321. this._removeDesignatedSlot(boundTexture);
  12322. }
  12323. this._boundTexturesCache[key] = null;
  12324. }
  12325. if (!this.disableTextureBindingOptimization) {
  12326. this._nextFreeTextureSlots = [];
  12327. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12328. this._nextFreeTextureSlots.push(slot);
  12329. }
  12330. }
  12331. this._currentTextureChannel = -1;
  12332. };
  12333. /**
  12334. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12335. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12336. * @returns true if engine is in deterministic lock step mode
  12337. */
  12338. Engine.prototype.isDeterministicLockStep = function () {
  12339. return this._deterministicLockstep;
  12340. };
  12341. /**
  12342. * Gets the max steps when engine is running in deterministic lock step
  12343. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12344. * @returns the max steps
  12345. */
  12346. Engine.prototype.getLockstepMaxSteps = function () {
  12347. return this._lockstepMaxSteps;
  12348. };
  12349. /**
  12350. * Gets an object containing information about the current webGL context
  12351. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12352. */
  12353. Engine.prototype.getGlInfo = function () {
  12354. return {
  12355. vendor: this._glVendor,
  12356. renderer: this._glRenderer,
  12357. version: this._glVersion
  12358. };
  12359. };
  12360. /**
  12361. * Gets current aspect ratio
  12362. * @param camera defines the camera to use to get the aspect ratio
  12363. * @param useScreen defines if screen size must be used (or the current render target if any)
  12364. * @returns a number defining the aspect ratio
  12365. */
  12366. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12367. if (useScreen === void 0) { useScreen = false; }
  12368. var viewport = camera.viewport;
  12369. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12370. };
  12371. /**
  12372. * Gets the current render width
  12373. * @param useScreen defines if screen size must be used (or the current render target if any)
  12374. * @returns a number defining the current render width
  12375. */
  12376. Engine.prototype.getRenderWidth = function (useScreen) {
  12377. if (useScreen === void 0) { useScreen = false; }
  12378. if (!useScreen && this._currentRenderTarget) {
  12379. return this._currentRenderTarget.width;
  12380. }
  12381. return this._gl.drawingBufferWidth;
  12382. };
  12383. /**
  12384. * Gets the current render height
  12385. * @param useScreen defines if screen size must be used (or the current render target if any)
  12386. * @returns a number defining the current render height
  12387. */
  12388. Engine.prototype.getRenderHeight = function (useScreen) {
  12389. if (useScreen === void 0) { useScreen = false; }
  12390. if (!useScreen && this._currentRenderTarget) {
  12391. return this._currentRenderTarget.height;
  12392. }
  12393. return this._gl.drawingBufferHeight;
  12394. };
  12395. /**
  12396. * Gets the HTML canvas attached with the current webGL context
  12397. * @returns a HTML canvas
  12398. */
  12399. Engine.prototype.getRenderingCanvas = function () {
  12400. return this._renderingCanvas;
  12401. };
  12402. /**
  12403. * Gets the client rect of the HTML canvas attached with the current webGL context
  12404. * @returns a client rectanglee
  12405. */
  12406. Engine.prototype.getRenderingCanvasClientRect = function () {
  12407. if (!this._renderingCanvas) {
  12408. return null;
  12409. }
  12410. return this._renderingCanvas.getBoundingClientRect();
  12411. };
  12412. /**
  12413. * Defines the hardware scaling level.
  12414. * By default the hardware scaling level is computed from the window device ratio.
  12415. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12416. * @param level defines the level to use
  12417. */
  12418. Engine.prototype.setHardwareScalingLevel = function (level) {
  12419. this._hardwareScalingLevel = level;
  12420. this.resize();
  12421. };
  12422. /**
  12423. * Gets the current hardware scaling level.
  12424. * By default the hardware scaling level is computed from the window device ratio.
  12425. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12426. * @returns a number indicating the current hardware scaling level
  12427. */
  12428. Engine.prototype.getHardwareScalingLevel = function () {
  12429. return this._hardwareScalingLevel;
  12430. };
  12431. /**
  12432. * Gets the list of loaded textures
  12433. * @returns an array containing all loaded textures
  12434. */
  12435. Engine.prototype.getLoadedTexturesCache = function () {
  12436. return this._internalTexturesCache;
  12437. };
  12438. /**
  12439. * Gets the object containing all engine capabilities
  12440. * @returns the EngineCapabilities object
  12441. */
  12442. Engine.prototype.getCaps = function () {
  12443. return this._caps;
  12444. };
  12445. Object.defineProperty(Engine.prototype, "drawCalls", {
  12446. /** @hidden */
  12447. get: function () {
  12448. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12449. return 0;
  12450. },
  12451. enumerable: true,
  12452. configurable: true
  12453. });
  12454. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12455. /** @hidden */
  12456. get: function () {
  12457. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12458. return null;
  12459. },
  12460. enumerable: true,
  12461. configurable: true
  12462. });
  12463. /**
  12464. * Gets the current depth function
  12465. * @returns a number defining the depth function
  12466. */
  12467. Engine.prototype.getDepthFunction = function () {
  12468. return this._depthCullingState.depthFunc;
  12469. };
  12470. /**
  12471. * Sets the current depth function
  12472. * @param depthFunc defines the function to use
  12473. */
  12474. Engine.prototype.setDepthFunction = function (depthFunc) {
  12475. this._depthCullingState.depthFunc = depthFunc;
  12476. };
  12477. /**
  12478. * Sets the current depth function to GREATER
  12479. */
  12480. Engine.prototype.setDepthFunctionToGreater = function () {
  12481. this._depthCullingState.depthFunc = this._gl.GREATER;
  12482. };
  12483. /**
  12484. * Sets the current depth function to GEQUAL
  12485. */
  12486. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12487. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12488. };
  12489. /**
  12490. * Sets the current depth function to LESS
  12491. */
  12492. Engine.prototype.setDepthFunctionToLess = function () {
  12493. this._depthCullingState.depthFunc = this._gl.LESS;
  12494. };
  12495. /**
  12496. * Sets the current depth function to LEQUAL
  12497. */
  12498. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12499. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12500. };
  12501. /**
  12502. * Gets a boolean indicating if stencil buffer is enabled
  12503. * @returns the current stencil buffer state
  12504. */
  12505. Engine.prototype.getStencilBuffer = function () {
  12506. return this._stencilState.stencilTest;
  12507. };
  12508. /**
  12509. * Enable or disable the stencil buffer
  12510. * @param enable defines if the stencil buffer must be enabled or disabled
  12511. */
  12512. Engine.prototype.setStencilBuffer = function (enable) {
  12513. this._stencilState.stencilTest = enable;
  12514. };
  12515. /**
  12516. * Gets the current stencil mask
  12517. * @returns a number defining the new stencil mask to use
  12518. */
  12519. Engine.prototype.getStencilMask = function () {
  12520. return this._stencilState.stencilMask;
  12521. };
  12522. /**
  12523. * Sets the current stencil mask
  12524. * @param mask defines the new stencil mask to use
  12525. */
  12526. Engine.prototype.setStencilMask = function (mask) {
  12527. this._stencilState.stencilMask = mask;
  12528. };
  12529. /**
  12530. * Gets the current stencil function
  12531. * @returns a number defining the stencil function to use
  12532. */
  12533. Engine.prototype.getStencilFunction = function () {
  12534. return this._stencilState.stencilFunc;
  12535. };
  12536. /**
  12537. * Gets the current stencil reference value
  12538. * @returns a number defining the stencil reference value to use
  12539. */
  12540. Engine.prototype.getStencilFunctionReference = function () {
  12541. return this._stencilState.stencilFuncRef;
  12542. };
  12543. /**
  12544. * Gets the current stencil mask
  12545. * @returns a number defining the stencil mask to use
  12546. */
  12547. Engine.prototype.getStencilFunctionMask = function () {
  12548. return this._stencilState.stencilFuncMask;
  12549. };
  12550. /**
  12551. * Sets the current stencil function
  12552. * @param stencilFunc defines the new stencil function to use
  12553. */
  12554. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12555. this._stencilState.stencilFunc = stencilFunc;
  12556. };
  12557. /**
  12558. * Sets the current stencil reference
  12559. * @param reference defines the new stencil reference to use
  12560. */
  12561. Engine.prototype.setStencilFunctionReference = function (reference) {
  12562. this._stencilState.stencilFuncRef = reference;
  12563. };
  12564. /**
  12565. * Sets the current stencil mask
  12566. * @param mask defines the new stencil mask to use
  12567. */
  12568. Engine.prototype.setStencilFunctionMask = function (mask) {
  12569. this._stencilState.stencilFuncMask = mask;
  12570. };
  12571. /**
  12572. * Gets the current stencil operation when stencil fails
  12573. * @returns a number defining stencil operation to use when stencil fails
  12574. */
  12575. Engine.prototype.getStencilOperationFail = function () {
  12576. return this._stencilState.stencilOpStencilFail;
  12577. };
  12578. /**
  12579. * Gets the current stencil operation when depth fails
  12580. * @returns a number defining stencil operation to use when depth fails
  12581. */
  12582. Engine.prototype.getStencilOperationDepthFail = function () {
  12583. return this._stencilState.stencilOpDepthFail;
  12584. };
  12585. /**
  12586. * Gets the current stencil operation when stencil passes
  12587. * @returns a number defining stencil operation to use when stencil passes
  12588. */
  12589. Engine.prototype.getStencilOperationPass = function () {
  12590. return this._stencilState.stencilOpStencilDepthPass;
  12591. };
  12592. /**
  12593. * Sets the stencil operation to use when stencil fails
  12594. * @param operation defines the stencil operation to use when stencil fails
  12595. */
  12596. Engine.prototype.setStencilOperationFail = function (operation) {
  12597. this._stencilState.stencilOpStencilFail = operation;
  12598. };
  12599. /**
  12600. * Sets the stencil operation to use when depth fails
  12601. * @param operation defines the stencil operation to use when depth fails
  12602. */
  12603. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12604. this._stencilState.stencilOpDepthFail = operation;
  12605. };
  12606. /**
  12607. * Sets the stencil operation to use when stencil passes
  12608. * @param operation defines the stencil operation to use when stencil passes
  12609. */
  12610. Engine.prototype.setStencilOperationPass = function (operation) {
  12611. this._stencilState.stencilOpStencilDepthPass = operation;
  12612. };
  12613. /**
  12614. * Sets a boolean indicating if the dithering state is enabled or disabled
  12615. * @param value defines the dithering state
  12616. */
  12617. Engine.prototype.setDitheringState = function (value) {
  12618. if (value) {
  12619. this._gl.enable(this._gl.DITHER);
  12620. }
  12621. else {
  12622. this._gl.disable(this._gl.DITHER);
  12623. }
  12624. };
  12625. /**
  12626. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12627. * @param value defines the rasterizer state
  12628. */
  12629. Engine.prototype.setRasterizerState = function (value) {
  12630. if (value) {
  12631. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12632. }
  12633. else {
  12634. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12635. }
  12636. };
  12637. /**
  12638. * stop executing a render loop function and remove it from the execution array
  12639. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12640. */
  12641. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12642. if (!renderFunction) {
  12643. this._activeRenderLoops = [];
  12644. return;
  12645. }
  12646. var index = this._activeRenderLoops.indexOf(renderFunction);
  12647. if (index >= 0) {
  12648. this._activeRenderLoops.splice(index, 1);
  12649. }
  12650. };
  12651. /** @hidden */
  12652. Engine.prototype._renderLoop = function () {
  12653. if (!this._contextWasLost) {
  12654. var shouldRender = true;
  12655. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12656. shouldRender = false;
  12657. }
  12658. if (shouldRender) {
  12659. // Start new frame
  12660. this.beginFrame();
  12661. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12662. var renderFunction = this._activeRenderLoops[index];
  12663. renderFunction();
  12664. }
  12665. // Present
  12666. this.endFrame();
  12667. }
  12668. }
  12669. if (this._activeRenderLoops.length > 0) {
  12670. // Register new frame
  12671. var requester = null;
  12672. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12673. requester = this._vrDisplay;
  12674. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12675. }
  12676. else {
  12677. this._renderingQueueLaunched = false;
  12678. }
  12679. };
  12680. /**
  12681. * Register and execute a render loop. The engine can have more than one render function
  12682. * @param renderFunction defines the function to continuously execute
  12683. */
  12684. Engine.prototype.runRenderLoop = function (renderFunction) {
  12685. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12686. return;
  12687. }
  12688. this._activeRenderLoops.push(renderFunction);
  12689. if (!this._renderingQueueLaunched) {
  12690. this._renderingQueueLaunched = true;
  12691. this._bindedRenderFunction = this._renderLoop.bind(this);
  12692. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12693. }
  12694. };
  12695. /**
  12696. * Toggle full screen mode
  12697. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12698. * @param options defines an option object to be sent to the requestFullscreen function
  12699. */
  12700. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12701. if (this.isFullscreen) {
  12702. BABYLON.Tools.ExitFullscreen();
  12703. }
  12704. else {
  12705. this._pointerLockRequested = requestPointerLock;
  12706. if (this._renderingCanvas) {
  12707. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12708. }
  12709. }
  12710. };
  12711. /**
  12712. * Clear the current render buffer or the current render target (if any is set up)
  12713. * @param color defines the color to use
  12714. * @param backBuffer defines if the back buffer must be cleared
  12715. * @param depth defines if the depth buffer must be cleared
  12716. * @param stencil defines if the stencil buffer must be cleared
  12717. */
  12718. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12719. if (stencil === void 0) { stencil = false; }
  12720. this.applyStates();
  12721. var mode = 0;
  12722. if (backBuffer && color) {
  12723. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12724. mode |= this._gl.COLOR_BUFFER_BIT;
  12725. }
  12726. if (depth) {
  12727. this._gl.clearDepth(1.0);
  12728. mode |= this._gl.DEPTH_BUFFER_BIT;
  12729. }
  12730. if (stencil) {
  12731. this._gl.clearStencil(0);
  12732. mode |= this._gl.STENCIL_BUFFER_BIT;
  12733. }
  12734. this._gl.clear(mode);
  12735. };
  12736. /**
  12737. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12738. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12739. * @param y defines the y-coordinate of the corner of the clear rectangle
  12740. * @param width defines the width of the clear rectangle
  12741. * @param height defines the height of the clear rectangle
  12742. * @param clearColor defines the clear color
  12743. */
  12744. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12745. var gl = this._gl;
  12746. // Save state
  12747. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12748. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12749. // Change state
  12750. gl.enable(gl.SCISSOR_TEST);
  12751. gl.scissor(x, y, width, height);
  12752. // Clear
  12753. this.clear(clearColor, true, true, true);
  12754. // Restore state
  12755. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12756. if (curScissor === true) {
  12757. gl.enable(gl.SCISSOR_TEST);
  12758. }
  12759. else {
  12760. gl.disable(gl.SCISSOR_TEST);
  12761. }
  12762. };
  12763. /**
  12764. * Set the WebGL's viewport
  12765. * @param viewport defines the viewport element to be used
  12766. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12767. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12768. */
  12769. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12770. var width = requiredWidth || this.getRenderWidth();
  12771. var height = requiredHeight || this.getRenderHeight();
  12772. var x = viewport.x || 0;
  12773. var y = viewport.y || 0;
  12774. this._cachedViewport = viewport;
  12775. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12776. };
  12777. /**
  12778. * Directly set the WebGL Viewport
  12779. * @param x defines the x coordinate of the viewport (in screen space)
  12780. * @param y defines the y coordinate of the viewport (in screen space)
  12781. * @param width defines the width of the viewport (in screen space)
  12782. * @param height defines the height of the viewport (in screen space)
  12783. * @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
  12784. */
  12785. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12786. var currentViewport = this._cachedViewport;
  12787. this._cachedViewport = null;
  12788. this._gl.viewport(x, y, width, height);
  12789. return currentViewport;
  12790. };
  12791. /**
  12792. * Begin a new frame
  12793. */
  12794. Engine.prototype.beginFrame = function () {
  12795. this.onBeginFrameObservable.notifyObservers(this);
  12796. this._measureFps();
  12797. };
  12798. /**
  12799. * Enf the current frame
  12800. */
  12801. Engine.prototype.endFrame = function () {
  12802. // Force a flush in case we are using a bad OS.
  12803. if (this._badOS) {
  12804. this.flushFramebuffer();
  12805. }
  12806. // Submit frame to the vr device, if enabled
  12807. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12808. // TODO: We should only submit the frame if we read frameData successfully.
  12809. this._vrDisplay.submitFrame();
  12810. }
  12811. this.onEndFrameObservable.notifyObservers(this);
  12812. };
  12813. /**
  12814. * Resize the view according to the canvas' size
  12815. */
  12816. Engine.prototype.resize = function () {
  12817. // We're not resizing the size of the canvas while in VR mode & presenting
  12818. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12819. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12820. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12821. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12822. }
  12823. };
  12824. /**
  12825. * Force a specific size of the canvas
  12826. * @param width defines the new canvas' width
  12827. * @param height defines the new canvas' height
  12828. */
  12829. Engine.prototype.setSize = function (width, height) {
  12830. if (!this._renderingCanvas) {
  12831. return;
  12832. }
  12833. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12834. return;
  12835. }
  12836. this._renderingCanvas.width = width;
  12837. this._renderingCanvas.height = height;
  12838. for (var index = 0; index < this.scenes.length; index++) {
  12839. var scene = this.scenes[index];
  12840. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12841. var cam = scene.cameras[camIndex];
  12842. cam._currentRenderId = 0;
  12843. }
  12844. }
  12845. if (this.onResizeObservable.hasObservers) {
  12846. this.onResizeObservable.notifyObservers(this);
  12847. }
  12848. };
  12849. // WebVR functions
  12850. /**
  12851. * Gets a boolean indicating if a webVR device was detected
  12852. * @returns true if a webVR device was detected
  12853. */
  12854. Engine.prototype.isVRDevicePresent = function () {
  12855. return !!this._vrDisplay;
  12856. };
  12857. /**
  12858. * Gets the current webVR device
  12859. * @returns the current webVR device (or null)
  12860. */
  12861. Engine.prototype.getVRDevice = function () {
  12862. return this._vrDisplay;
  12863. };
  12864. /**
  12865. * Initializes a webVR display and starts listening to display change events
  12866. * The onVRDisplayChangedObservable will be notified upon these changes
  12867. * @returns The onVRDisplayChangedObservable
  12868. */
  12869. Engine.prototype.initWebVR = function () {
  12870. this.initWebVRAsync();
  12871. return this.onVRDisplayChangedObservable;
  12872. };
  12873. /**
  12874. * Initializes a webVR display and starts listening to display change events
  12875. * The onVRDisplayChangedObservable will be notified upon these changes
  12876. * @returns A promise containing a VRDisplay and if vr is supported
  12877. */
  12878. Engine.prototype.initWebVRAsync = function () {
  12879. var _this = this;
  12880. var notifyObservers = function () {
  12881. var eventArgs = {
  12882. vrDisplay: _this._vrDisplay,
  12883. vrSupported: _this._vrSupported
  12884. };
  12885. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12886. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12887. };
  12888. if (!this._onVrDisplayConnect) {
  12889. this._onVrDisplayConnect = function (event) {
  12890. _this._vrDisplay = event.display;
  12891. notifyObservers();
  12892. };
  12893. this._onVrDisplayDisconnect = function () {
  12894. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12895. _this._vrDisplay = undefined;
  12896. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12897. notifyObservers();
  12898. };
  12899. this._onVrDisplayPresentChange = function () {
  12900. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12901. };
  12902. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12903. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12904. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12905. }
  12906. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12907. this._webVRInitPromise.then(notifyObservers);
  12908. return this._webVRInitPromise;
  12909. };
  12910. /**
  12911. * Call this function to switch to webVR mode
  12912. * Will do nothing if webVR is not supported or if there is no webVR device
  12913. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12914. */
  12915. Engine.prototype.enableVR = function () {
  12916. var _this = this;
  12917. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12918. var onResolved = function () {
  12919. _this.onVRRequestPresentComplete.notifyObservers(true);
  12920. _this._onVRFullScreenTriggered();
  12921. };
  12922. var onRejected = function () {
  12923. _this.onVRRequestPresentComplete.notifyObservers(false);
  12924. };
  12925. this.onVRRequestPresentStart.notifyObservers(this);
  12926. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12927. }
  12928. };
  12929. /**
  12930. * Call this function to leave webVR mode
  12931. * Will do nothing if webVR is not supported or if there is no webVR device
  12932. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12933. */
  12934. Engine.prototype.disableVR = function () {
  12935. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12936. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12937. }
  12938. };
  12939. Engine.prototype._getVRDisplaysAsync = function () {
  12940. var _this = this;
  12941. return new Promise(function (res, rej) {
  12942. if (navigator.getVRDisplays) {
  12943. navigator.getVRDisplays().then(function (devices) {
  12944. _this._vrSupported = true;
  12945. // note that devices may actually be an empty array. This is fine;
  12946. // we expect this._vrDisplay to be undefined in this case.
  12947. _this._vrDisplay = devices[0];
  12948. res({
  12949. vrDisplay: _this._vrDisplay,
  12950. vrSupported: _this._vrSupported
  12951. });
  12952. });
  12953. }
  12954. else {
  12955. _this._vrDisplay = undefined;
  12956. _this._vrSupported = false;
  12957. res({
  12958. vrDisplay: _this._vrDisplay,
  12959. vrSupported: _this._vrSupported
  12960. });
  12961. }
  12962. });
  12963. };
  12964. /**
  12965. * Binds the frame buffer to the specified texture.
  12966. * @param texture The texture to render to or null for the default canvas
  12967. * @param faceIndex The face of the texture to render to in case of cube texture
  12968. * @param requiredWidth The width of the target to render to
  12969. * @param requiredHeight The height of the target to render to
  12970. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12971. * @param depthStencilTexture The depth stencil texture to use to render
  12972. */
  12973. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12974. if (this._currentRenderTarget) {
  12975. this.unBindFramebuffer(this._currentRenderTarget);
  12976. }
  12977. this._currentRenderTarget = texture;
  12978. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12979. var gl = this._gl;
  12980. if (texture.isCube) {
  12981. if (faceIndex === undefined) {
  12982. faceIndex = 0;
  12983. }
  12984. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12985. if (depthStencilTexture) {
  12986. if (depthStencilTexture._generateStencilBuffer) {
  12987. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12988. }
  12989. else {
  12990. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12991. }
  12992. }
  12993. }
  12994. if (this._cachedViewport && !forceFullscreenViewport) {
  12995. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12996. }
  12997. else {
  12998. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12999. }
  13000. this.wipeCaches();
  13001. };
  13002. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13003. if (this._currentFramebuffer !== framebuffer) {
  13004. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13005. this._currentFramebuffer = framebuffer;
  13006. }
  13007. };
  13008. /**
  13009. * Unbind the current render target texture from the webGL context
  13010. * @param texture defines the render target texture to unbind
  13011. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13012. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13013. */
  13014. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13015. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13016. this._currentRenderTarget = null;
  13017. // If MSAA, we need to bitblt back to main texture
  13018. var gl = this._gl;
  13019. if (texture._MSAAFramebuffer) {
  13020. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13021. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13022. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13023. }
  13024. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13025. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13026. gl.generateMipmap(gl.TEXTURE_2D);
  13027. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13028. }
  13029. if (onBeforeUnbind) {
  13030. if (texture._MSAAFramebuffer) {
  13031. // Bind the correct framebuffer
  13032. this.bindUnboundFramebuffer(texture._framebuffer);
  13033. }
  13034. onBeforeUnbind();
  13035. }
  13036. this.bindUnboundFramebuffer(null);
  13037. };
  13038. /**
  13039. * Unbind a list of render target textures from the webGL context
  13040. * This is used only when drawBuffer extension or webGL2 are active
  13041. * @param textures defines the render target textures to unbind
  13042. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13043. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13044. */
  13045. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13046. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13047. this._currentRenderTarget = null;
  13048. // If MSAA, we need to bitblt back to main texture
  13049. var gl = this._gl;
  13050. if (textures[0]._MSAAFramebuffer) {
  13051. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13052. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13053. var attachments = textures[0]._attachments;
  13054. if (!attachments) {
  13055. attachments = new Array(textures.length);
  13056. textures[0]._attachments = attachments;
  13057. }
  13058. for (var i = 0; i < textures.length; i++) {
  13059. var texture = textures[i];
  13060. for (var j = 0; j < attachments.length; j++) {
  13061. attachments[j] = gl.NONE;
  13062. }
  13063. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13064. gl.readBuffer(attachments[i]);
  13065. gl.drawBuffers(attachments);
  13066. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13067. }
  13068. for (var i = 0; i < attachments.length; i++) {
  13069. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13070. }
  13071. gl.drawBuffers(attachments);
  13072. }
  13073. for (var i = 0; i < textures.length; i++) {
  13074. var texture = textures[i];
  13075. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13076. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13077. gl.generateMipmap(gl.TEXTURE_2D);
  13078. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13079. }
  13080. }
  13081. if (onBeforeUnbind) {
  13082. if (textures[0]._MSAAFramebuffer) {
  13083. // Bind the correct framebuffer
  13084. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13085. }
  13086. onBeforeUnbind();
  13087. }
  13088. this.bindUnboundFramebuffer(null);
  13089. };
  13090. /**
  13091. * Force the mipmap generation for the given render target texture
  13092. * @param texture defines the render target texture to use
  13093. */
  13094. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13095. if (texture.generateMipMaps) {
  13096. var gl = this._gl;
  13097. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13098. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13099. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13100. }
  13101. };
  13102. /**
  13103. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13104. */
  13105. Engine.prototype.flushFramebuffer = function () {
  13106. this._gl.flush();
  13107. };
  13108. /**
  13109. * Unbind the current render target and bind the default framebuffer
  13110. */
  13111. Engine.prototype.restoreDefaultFramebuffer = function () {
  13112. if (this._currentRenderTarget) {
  13113. this.unBindFramebuffer(this._currentRenderTarget);
  13114. }
  13115. else {
  13116. this.bindUnboundFramebuffer(null);
  13117. }
  13118. if (this._cachedViewport) {
  13119. this.setViewport(this._cachedViewport);
  13120. }
  13121. this.wipeCaches();
  13122. };
  13123. // UBOs
  13124. /**
  13125. * Create an uniform buffer
  13126. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13127. * @param elements defines the content of the uniform buffer
  13128. * @returns the webGL uniform buffer
  13129. */
  13130. Engine.prototype.createUniformBuffer = function (elements) {
  13131. var ubo = this._gl.createBuffer();
  13132. if (!ubo) {
  13133. throw new Error("Unable to create uniform buffer");
  13134. }
  13135. this.bindUniformBuffer(ubo);
  13136. if (elements instanceof Float32Array) {
  13137. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13138. }
  13139. else {
  13140. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13141. }
  13142. this.bindUniformBuffer(null);
  13143. ubo.references = 1;
  13144. return ubo;
  13145. };
  13146. /**
  13147. * Create a dynamic uniform buffer
  13148. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13149. * @param elements defines the content of the uniform buffer
  13150. * @returns the webGL uniform buffer
  13151. */
  13152. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13153. var ubo = this._gl.createBuffer();
  13154. if (!ubo) {
  13155. throw new Error("Unable to create dynamic uniform buffer");
  13156. }
  13157. this.bindUniformBuffer(ubo);
  13158. if (elements instanceof Float32Array) {
  13159. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13160. }
  13161. else {
  13162. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13163. }
  13164. this.bindUniformBuffer(null);
  13165. ubo.references = 1;
  13166. return ubo;
  13167. };
  13168. /**
  13169. * Update an existing uniform buffer
  13170. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13171. * @param uniformBuffer defines the target uniform buffer
  13172. * @param elements defines the content to update
  13173. * @param offset defines the offset in the uniform buffer where update should start
  13174. * @param count defines the size of the data to update
  13175. */
  13176. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13177. this.bindUniformBuffer(uniformBuffer);
  13178. if (offset === undefined) {
  13179. offset = 0;
  13180. }
  13181. if (count === undefined) {
  13182. if (elements instanceof Float32Array) {
  13183. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13184. }
  13185. else {
  13186. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13187. }
  13188. }
  13189. else {
  13190. if (elements instanceof Float32Array) {
  13191. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13192. }
  13193. else {
  13194. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13195. }
  13196. }
  13197. this.bindUniformBuffer(null);
  13198. };
  13199. // VBOs
  13200. Engine.prototype._resetVertexBufferBinding = function () {
  13201. this.bindArrayBuffer(null);
  13202. this._cachedVertexBuffers = null;
  13203. };
  13204. /**
  13205. * Creates a vertex buffer
  13206. * @param data the data for the vertex buffer
  13207. * @returns the new WebGL static buffer
  13208. */
  13209. Engine.prototype.createVertexBuffer = function (data) {
  13210. var vbo = this._gl.createBuffer();
  13211. if (!vbo) {
  13212. throw new Error("Unable to create vertex buffer");
  13213. }
  13214. this.bindArrayBuffer(vbo);
  13215. if (data instanceof Array) {
  13216. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13217. }
  13218. else {
  13219. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13220. }
  13221. this._resetVertexBufferBinding();
  13222. vbo.references = 1;
  13223. return vbo;
  13224. };
  13225. /**
  13226. * Creates a dynamic vertex buffer
  13227. * @param data the data for the dynamic vertex buffer
  13228. * @returns the new WebGL dynamic buffer
  13229. */
  13230. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13231. var vbo = this._gl.createBuffer();
  13232. if (!vbo) {
  13233. throw new Error("Unable to create dynamic vertex buffer");
  13234. }
  13235. this.bindArrayBuffer(vbo);
  13236. if (data instanceof Array) {
  13237. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13238. }
  13239. else {
  13240. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13241. }
  13242. this._resetVertexBufferBinding();
  13243. vbo.references = 1;
  13244. return vbo;
  13245. };
  13246. /**
  13247. * Update a dynamic index buffer
  13248. * @param indexBuffer defines the target index buffer
  13249. * @param indices defines the data to update
  13250. * @param offset defines the offset in the target index buffer where update should start
  13251. */
  13252. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13253. if (offset === void 0) { offset = 0; }
  13254. // Force cache update
  13255. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13256. this.bindIndexBuffer(indexBuffer);
  13257. var arrayBuffer;
  13258. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13259. arrayBuffer = indices;
  13260. }
  13261. else {
  13262. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13263. }
  13264. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13265. this._resetIndexBufferBinding();
  13266. };
  13267. /**
  13268. * Updates a dynamic vertex buffer.
  13269. * @param vertexBuffer the vertex buffer to update
  13270. * @param data the data used to update the vertex buffer
  13271. * @param byteOffset the byte offset of the data
  13272. * @param byteLength the byte length of the data
  13273. */
  13274. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13275. this.bindArrayBuffer(vertexBuffer);
  13276. if (byteOffset === undefined) {
  13277. byteOffset = 0;
  13278. }
  13279. if (byteLength === undefined) {
  13280. if (data instanceof Array) {
  13281. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13282. }
  13283. else {
  13284. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13285. }
  13286. }
  13287. else {
  13288. if (data instanceof Array) {
  13289. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13290. }
  13291. else {
  13292. if (data instanceof ArrayBuffer) {
  13293. data = new Uint8Array(data, byteOffset, byteLength);
  13294. }
  13295. else {
  13296. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13297. }
  13298. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13299. }
  13300. }
  13301. this._resetVertexBufferBinding();
  13302. };
  13303. Engine.prototype._resetIndexBufferBinding = function () {
  13304. this.bindIndexBuffer(null);
  13305. this._cachedIndexBuffer = null;
  13306. };
  13307. /**
  13308. * Creates a new index buffer
  13309. * @param indices defines the content of the index buffer
  13310. * @param updatable defines if the index buffer must be updatable
  13311. * @returns a new webGL buffer
  13312. */
  13313. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13314. var vbo = this._gl.createBuffer();
  13315. if (!vbo) {
  13316. throw new Error("Unable to create index buffer");
  13317. }
  13318. this.bindIndexBuffer(vbo);
  13319. // Check for 32 bits indices
  13320. var arrayBuffer;
  13321. var need32Bits = false;
  13322. if (indices instanceof Uint16Array) {
  13323. arrayBuffer = indices;
  13324. }
  13325. else {
  13326. //check 32 bit support
  13327. if (this._caps.uintIndices) {
  13328. if (indices instanceof Uint32Array) {
  13329. arrayBuffer = indices;
  13330. need32Bits = true;
  13331. }
  13332. else {
  13333. //number[] or Int32Array, check if 32 bit is necessary
  13334. for (var index = 0; index < indices.length; index++) {
  13335. if (indices[index] > 65535) {
  13336. need32Bits = true;
  13337. break;
  13338. }
  13339. }
  13340. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13341. }
  13342. }
  13343. else {
  13344. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13345. arrayBuffer = new Uint16Array(indices);
  13346. }
  13347. }
  13348. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13349. this._resetIndexBufferBinding();
  13350. vbo.references = 1;
  13351. vbo.is32Bits = need32Bits;
  13352. return vbo;
  13353. };
  13354. /**
  13355. * Bind a webGL buffer to the webGL context
  13356. * @param buffer defines the buffer to bind
  13357. */
  13358. Engine.prototype.bindArrayBuffer = function (buffer) {
  13359. if (!this._vaoRecordInProgress) {
  13360. this._unbindVertexArrayObject();
  13361. }
  13362. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13363. };
  13364. /**
  13365. * Bind an uniform buffer to the current webGL context
  13366. * @param buffer defines the buffer to bind
  13367. */
  13368. Engine.prototype.bindUniformBuffer = function (buffer) {
  13369. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13370. };
  13371. /**
  13372. * Bind a buffer to the current webGL context at a given location
  13373. * @param buffer defines the buffer to bind
  13374. * @param location defines the index where to bind the buffer
  13375. */
  13376. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13377. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13378. };
  13379. /**
  13380. * Bind a specific block at a given index in a specific shader program
  13381. * @param shaderProgram defines the shader program
  13382. * @param blockName defines the block name
  13383. * @param index defines the index where to bind the block
  13384. */
  13385. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13386. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13387. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13388. };
  13389. ;
  13390. Engine.prototype.bindIndexBuffer = function (buffer) {
  13391. if (!this._vaoRecordInProgress) {
  13392. this._unbindVertexArrayObject();
  13393. }
  13394. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13395. };
  13396. Engine.prototype.bindBuffer = function (buffer, target) {
  13397. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13398. this._gl.bindBuffer(target, buffer);
  13399. this._currentBoundBuffer[target] = buffer;
  13400. }
  13401. };
  13402. /**
  13403. * update the bound buffer with the given data
  13404. * @param data defines the data to update
  13405. */
  13406. Engine.prototype.updateArrayBuffer = function (data) {
  13407. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13408. };
  13409. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13410. var pointer = this._currentBufferPointers[indx];
  13411. var changed = false;
  13412. if (!pointer.active) {
  13413. changed = true;
  13414. pointer.active = true;
  13415. pointer.index = indx;
  13416. pointer.size = size;
  13417. pointer.type = type;
  13418. pointer.normalized = normalized;
  13419. pointer.stride = stride;
  13420. pointer.offset = offset;
  13421. pointer.buffer = buffer;
  13422. }
  13423. else {
  13424. if (pointer.buffer !== buffer) {
  13425. pointer.buffer = buffer;
  13426. changed = true;
  13427. }
  13428. if (pointer.size !== size) {
  13429. pointer.size = size;
  13430. changed = true;
  13431. }
  13432. if (pointer.type !== type) {
  13433. pointer.type = type;
  13434. changed = true;
  13435. }
  13436. if (pointer.normalized !== normalized) {
  13437. pointer.normalized = normalized;
  13438. changed = true;
  13439. }
  13440. if (pointer.stride !== stride) {
  13441. pointer.stride = stride;
  13442. changed = true;
  13443. }
  13444. if (pointer.offset !== offset) {
  13445. pointer.offset = offset;
  13446. changed = true;
  13447. }
  13448. }
  13449. if (changed || this._vaoRecordInProgress) {
  13450. this.bindArrayBuffer(buffer);
  13451. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13452. }
  13453. };
  13454. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13455. if (indexBuffer == null) {
  13456. return;
  13457. }
  13458. if (this._cachedIndexBuffer !== indexBuffer) {
  13459. this._cachedIndexBuffer = indexBuffer;
  13460. this.bindIndexBuffer(indexBuffer);
  13461. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13462. }
  13463. };
  13464. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13465. var attributes = effect.getAttributesNames();
  13466. if (!this._vaoRecordInProgress) {
  13467. this._unbindVertexArrayObject();
  13468. }
  13469. this.unbindAllAttributes();
  13470. for (var index = 0; index < attributes.length; index++) {
  13471. var order = effect.getAttributeLocation(index);
  13472. if (order >= 0) {
  13473. var vertexBuffer = vertexBuffers[attributes[index]];
  13474. if (!vertexBuffer) {
  13475. continue;
  13476. }
  13477. this._gl.enableVertexAttribArray(order);
  13478. if (!this._vaoRecordInProgress) {
  13479. this._vertexAttribArraysEnabled[order] = true;
  13480. }
  13481. var buffer = vertexBuffer.getBuffer();
  13482. if (buffer) {
  13483. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13484. if (vertexBuffer.getIsInstanced()) {
  13485. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13486. if (!this._vaoRecordInProgress) {
  13487. this._currentInstanceLocations.push(order);
  13488. this._currentInstanceBuffers.push(buffer);
  13489. }
  13490. }
  13491. }
  13492. }
  13493. }
  13494. };
  13495. /**
  13496. * Records a vertex array object
  13497. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13498. * @param vertexBuffers defines the list of vertex buffers to store
  13499. * @param indexBuffer defines the index buffer to store
  13500. * @param effect defines the effect to store
  13501. * @returns the new vertex array object
  13502. */
  13503. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13504. var vao = this._gl.createVertexArray();
  13505. this._vaoRecordInProgress = true;
  13506. this._gl.bindVertexArray(vao);
  13507. this._mustWipeVertexAttributes = true;
  13508. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13509. this.bindIndexBuffer(indexBuffer);
  13510. this._vaoRecordInProgress = false;
  13511. this._gl.bindVertexArray(null);
  13512. return vao;
  13513. };
  13514. /**
  13515. * Bind a specific vertex array object
  13516. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13517. * @param vertexArrayObject defines the vertex array object to bind
  13518. * @param indexBuffer defines the index buffer to bind
  13519. */
  13520. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13521. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13522. this._cachedVertexArrayObject = vertexArrayObject;
  13523. this._gl.bindVertexArray(vertexArrayObject);
  13524. this._cachedVertexBuffers = null;
  13525. this._cachedIndexBuffer = null;
  13526. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13527. this._mustWipeVertexAttributes = true;
  13528. }
  13529. };
  13530. /**
  13531. * Bind webGl buffers directly to the webGL context
  13532. * @param vertexBuffer defines the vertex buffer to bind
  13533. * @param indexBuffer defines the index buffer to bind
  13534. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13535. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13536. * @param effect defines the effect associated with the vertex buffer
  13537. */
  13538. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13539. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13540. this._cachedVertexBuffers = vertexBuffer;
  13541. this._cachedEffectForVertexBuffers = effect;
  13542. var attributesCount = effect.getAttributesCount();
  13543. this._unbindVertexArrayObject();
  13544. this.unbindAllAttributes();
  13545. var offset = 0;
  13546. for (var index = 0; index < attributesCount; index++) {
  13547. if (index < vertexDeclaration.length) {
  13548. var order = effect.getAttributeLocation(index);
  13549. if (order >= 0) {
  13550. this._gl.enableVertexAttribArray(order);
  13551. this._vertexAttribArraysEnabled[order] = true;
  13552. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13553. }
  13554. offset += vertexDeclaration[index] * 4;
  13555. }
  13556. }
  13557. }
  13558. this._bindIndexBufferWithCache(indexBuffer);
  13559. };
  13560. Engine.prototype._unbindVertexArrayObject = function () {
  13561. if (!this._cachedVertexArrayObject) {
  13562. return;
  13563. }
  13564. this._cachedVertexArrayObject = null;
  13565. this._gl.bindVertexArray(null);
  13566. };
  13567. /**
  13568. * Bind a list of vertex buffers to the webGL context
  13569. * @param vertexBuffers defines the list of vertex buffers to bind
  13570. * @param indexBuffer defines the index buffer to bind
  13571. * @param effect defines the effect associated with the vertex buffers
  13572. */
  13573. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13574. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13575. this._cachedVertexBuffers = vertexBuffers;
  13576. this._cachedEffectForVertexBuffers = effect;
  13577. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13578. }
  13579. this._bindIndexBufferWithCache(indexBuffer);
  13580. };
  13581. /**
  13582. * Unbind all instance attributes
  13583. */
  13584. Engine.prototype.unbindInstanceAttributes = function () {
  13585. var boundBuffer;
  13586. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13587. var instancesBuffer = this._currentInstanceBuffers[i];
  13588. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13589. boundBuffer = instancesBuffer;
  13590. this.bindArrayBuffer(instancesBuffer);
  13591. }
  13592. var offsetLocation = this._currentInstanceLocations[i];
  13593. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13594. }
  13595. this._currentInstanceBuffers.length = 0;
  13596. this._currentInstanceLocations.length = 0;
  13597. };
  13598. /**
  13599. * Release and free the memory of a vertex array object
  13600. * @param vao defines the vertex array object to delete
  13601. */
  13602. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13603. this._gl.deleteVertexArray(vao);
  13604. };
  13605. /** @hidden */
  13606. Engine.prototype._releaseBuffer = function (buffer) {
  13607. buffer.references--;
  13608. if (buffer.references === 0) {
  13609. this._gl.deleteBuffer(buffer);
  13610. return true;
  13611. }
  13612. return false;
  13613. };
  13614. /**
  13615. * Creates a webGL buffer to use with instanciation
  13616. * @param capacity defines the size of the buffer
  13617. * @returns the webGL buffer
  13618. */
  13619. Engine.prototype.createInstancesBuffer = function (capacity) {
  13620. var buffer = this._gl.createBuffer();
  13621. if (!buffer) {
  13622. throw new Error("Unable to create instance buffer");
  13623. }
  13624. buffer.capacity = capacity;
  13625. this.bindArrayBuffer(buffer);
  13626. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13627. return buffer;
  13628. };
  13629. /**
  13630. * Delete a webGL buffer used with instanciation
  13631. * @param buffer defines the webGL buffer to delete
  13632. */
  13633. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13634. this._gl.deleteBuffer(buffer);
  13635. };
  13636. /**
  13637. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13638. * @param instancesBuffer defines the webGL buffer to update and bind
  13639. * @param data defines the data to store in the buffer
  13640. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13641. */
  13642. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13643. this.bindArrayBuffer(instancesBuffer);
  13644. if (data) {
  13645. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13646. }
  13647. if (offsetLocations[0].index !== undefined) {
  13648. var stride = 0;
  13649. for (var i = 0; i < offsetLocations.length; i++) {
  13650. var ai = offsetLocations[i];
  13651. stride += ai.attributeSize * 4;
  13652. }
  13653. for (var i = 0; i < offsetLocations.length; i++) {
  13654. var ai = offsetLocations[i];
  13655. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13656. this._gl.enableVertexAttribArray(ai.index);
  13657. this._vertexAttribArraysEnabled[ai.index] = true;
  13658. }
  13659. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13660. this._gl.vertexAttribDivisor(ai.index, 1);
  13661. this._currentInstanceLocations.push(ai.index);
  13662. this._currentInstanceBuffers.push(instancesBuffer);
  13663. }
  13664. }
  13665. else {
  13666. for (var index = 0; index < 4; index++) {
  13667. var offsetLocation = offsetLocations[index];
  13668. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13669. this._gl.enableVertexAttribArray(offsetLocation);
  13670. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13671. }
  13672. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13673. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13674. this._currentInstanceLocations.push(offsetLocation);
  13675. this._currentInstanceBuffers.push(instancesBuffer);
  13676. }
  13677. }
  13678. };
  13679. /**
  13680. * Apply all cached states (depth, culling, stencil and alpha)
  13681. */
  13682. Engine.prototype.applyStates = function () {
  13683. this._depthCullingState.apply(this._gl);
  13684. this._stencilState.apply(this._gl);
  13685. this._alphaState.apply(this._gl);
  13686. };
  13687. /**
  13688. * Send a draw order
  13689. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13690. * @param indexStart defines the starting index
  13691. * @param indexCount defines the number of index to draw
  13692. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13693. */
  13694. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13695. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13696. };
  13697. /**
  13698. * Draw a list of points
  13699. * @param verticesStart defines the index of first vertex to draw
  13700. * @param verticesCount defines the count of vertices to draw
  13701. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13702. */
  13703. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13704. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13705. };
  13706. /**
  13707. * Draw a list of unindexed primitives
  13708. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13709. * @param verticesStart defines the index of first vertex to draw
  13710. * @param verticesCount defines the count of vertices to draw
  13711. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13712. */
  13713. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13714. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13715. };
  13716. /**
  13717. * Draw a list of indexed primitives
  13718. * @param fillMode defines the primitive to use
  13719. * @param indexStart defines the starting index
  13720. * @param indexCount defines the number of index to draw
  13721. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13722. */
  13723. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13724. // Apply states
  13725. this.applyStates();
  13726. this._drawCalls.addCount(1, false);
  13727. // Render
  13728. var drawMode = this._drawMode(fillMode);
  13729. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13730. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13731. if (instancesCount) {
  13732. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13733. }
  13734. else {
  13735. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13736. }
  13737. };
  13738. /**
  13739. * Draw a list of unindexed primitives
  13740. * @param fillMode defines the primitive to use
  13741. * @param verticesStart defines the index of first vertex to draw
  13742. * @param verticesCount defines the count of vertices to draw
  13743. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13744. */
  13745. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13746. // Apply states
  13747. this.applyStates();
  13748. this._drawCalls.addCount(1, false);
  13749. var drawMode = this._drawMode(fillMode);
  13750. if (instancesCount) {
  13751. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13752. }
  13753. else {
  13754. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13755. }
  13756. };
  13757. Engine.prototype._drawMode = function (fillMode) {
  13758. switch (fillMode) {
  13759. // Triangle views
  13760. case BABYLON.Material.TriangleFillMode:
  13761. return this._gl.TRIANGLES;
  13762. case BABYLON.Material.PointFillMode:
  13763. return this._gl.POINTS;
  13764. case BABYLON.Material.WireFrameFillMode:
  13765. return this._gl.LINES;
  13766. // Draw modes
  13767. case BABYLON.Material.PointListDrawMode:
  13768. return this._gl.POINTS;
  13769. case BABYLON.Material.LineListDrawMode:
  13770. return this._gl.LINES;
  13771. case BABYLON.Material.LineLoopDrawMode:
  13772. return this._gl.LINE_LOOP;
  13773. case BABYLON.Material.LineStripDrawMode:
  13774. return this._gl.LINE_STRIP;
  13775. case BABYLON.Material.TriangleStripDrawMode:
  13776. return this._gl.TRIANGLE_STRIP;
  13777. case BABYLON.Material.TriangleFanDrawMode:
  13778. return this._gl.TRIANGLE_FAN;
  13779. default:
  13780. return this._gl.TRIANGLES;
  13781. }
  13782. };
  13783. // Shaders
  13784. /** @hidden */
  13785. Engine.prototype._releaseEffect = function (effect) {
  13786. if (this._compiledEffects[effect._key]) {
  13787. delete this._compiledEffects[effect._key];
  13788. this._deleteProgram(effect.getProgram());
  13789. }
  13790. };
  13791. /** @hidden */
  13792. Engine.prototype._deleteProgram = function (program) {
  13793. if (program) {
  13794. program.__SPECTOR_rebuildProgram = null;
  13795. if (program.transformFeedback) {
  13796. this.deleteTransformFeedback(program.transformFeedback);
  13797. program.transformFeedback = null;
  13798. }
  13799. this._gl.deleteProgram(program);
  13800. }
  13801. };
  13802. /**
  13803. * Create a new effect (used to store vertex/fragment shaders)
  13804. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13805. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13806. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13807. * @param samplers defines an array of string used to represent textures
  13808. * @param defines defines the string containing the defines to use to compile the shaders
  13809. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13810. * @param onCompiled defines a function to call when the effect creation is successful
  13811. * @param onError defines a function to call when the effect creation has failed
  13812. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13813. * @returns the new Effect
  13814. */
  13815. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13816. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13817. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13818. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13819. if (this._compiledEffects[name]) {
  13820. var compiledEffect = this._compiledEffects[name];
  13821. if (onCompiled && compiledEffect.isReady()) {
  13822. onCompiled(compiledEffect);
  13823. }
  13824. return compiledEffect;
  13825. }
  13826. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13827. effect._key = name;
  13828. this._compiledEffects[name] = effect;
  13829. return effect;
  13830. };
  13831. /**
  13832. * Create an effect to use with particle systems
  13833. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13834. * @param uniformsNames defines a list of attribute names
  13835. * @param samplers defines an array of string used to represent textures
  13836. * @param defines defines the string containing the defines to use to compile the shaders
  13837. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13838. * @param onCompiled defines a function to call when the effect creation is successful
  13839. * @param onError defines a function to call when the effect creation has failed
  13840. * @returns the new Effect
  13841. */
  13842. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13843. if (uniformsNames === void 0) { uniformsNames = []; }
  13844. if (samplers === void 0) { samplers = []; }
  13845. if (defines === void 0) { defines = ""; }
  13846. return this.createEffect({
  13847. vertex: "particles",
  13848. fragmentElement: fragmentName
  13849. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13850. };
  13851. /**
  13852. * Directly creates a webGL program
  13853. * @param vertexCode defines the vertex shader code to use
  13854. * @param fragmentCode defines the fragment shader code to use
  13855. * @param context defines the webGL context to use (if not set, the current one will be used)
  13856. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13857. * @returns the new webGL program
  13858. */
  13859. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13860. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13861. context = context || this._gl;
  13862. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13863. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13864. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13865. };
  13866. /**
  13867. * Creates a webGL program
  13868. * @param vertexCode defines the vertex shader code to use
  13869. * @param fragmentCode defines the fragment shader code to use
  13870. * @param defines defines the string containing the defines to use to compile the shaders
  13871. * @param context defines the webGL context to use (if not set, the current one will be used)
  13872. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13873. * @returns the new webGL program
  13874. */
  13875. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13876. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13877. context = context || this._gl;
  13878. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13879. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13880. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13881. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13882. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13883. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13884. return program;
  13885. };
  13886. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13887. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13888. var shaderProgram = context.createProgram();
  13889. if (!shaderProgram) {
  13890. throw new Error("Unable to create program");
  13891. }
  13892. context.attachShader(shaderProgram, vertexShader);
  13893. context.attachShader(shaderProgram, fragmentShader);
  13894. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13895. var transformFeedback = this.createTransformFeedback();
  13896. this.bindTransformFeedback(transformFeedback);
  13897. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13898. shaderProgram.transformFeedback = transformFeedback;
  13899. }
  13900. context.linkProgram(shaderProgram);
  13901. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13902. this.bindTransformFeedback(null);
  13903. }
  13904. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13905. if (!linked) {
  13906. context.validateProgram(shaderProgram);
  13907. var error = context.getProgramInfoLog(shaderProgram);
  13908. if (error) {
  13909. throw new Error(error);
  13910. }
  13911. }
  13912. context.deleteShader(vertexShader);
  13913. context.deleteShader(fragmentShader);
  13914. return shaderProgram;
  13915. };
  13916. /**
  13917. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13918. * @param shaderProgram defines the webGL program to use
  13919. * @param uniformsNames defines the list of uniform names
  13920. * @returns an array of webGL uniform locations
  13921. */
  13922. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13923. var results = new Array();
  13924. for (var index = 0; index < uniformsNames.length; index++) {
  13925. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13926. }
  13927. return results;
  13928. };
  13929. /**
  13930. * Gets the lsit of active attributes for a given webGL program
  13931. * @param shaderProgram defines the webGL program to use
  13932. * @param attributesNames defines the list of attribute names to get
  13933. * @returns an array of indices indicating the offset of each attribute
  13934. */
  13935. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13936. var results = [];
  13937. for (var index = 0; index < attributesNames.length; index++) {
  13938. try {
  13939. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13940. }
  13941. catch (e) {
  13942. results.push(-1);
  13943. }
  13944. }
  13945. return results;
  13946. };
  13947. /**
  13948. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13949. * @param effect defines the effect to activate
  13950. */
  13951. Engine.prototype.enableEffect = function (effect) {
  13952. if (!effect) {
  13953. return;
  13954. }
  13955. // Use program
  13956. this.bindSamplers(effect);
  13957. this._currentEffect = effect;
  13958. if (effect.onBind) {
  13959. effect.onBind(effect);
  13960. }
  13961. effect.onBindObservable.notifyObservers(effect);
  13962. };
  13963. /**
  13964. * Set the value of an uniform to an array of int32
  13965. * @param uniform defines the webGL uniform location where to store the value
  13966. * @param array defines the array of int32 to store
  13967. */
  13968. Engine.prototype.setIntArray = function (uniform, array) {
  13969. if (!uniform)
  13970. return;
  13971. this._gl.uniform1iv(uniform, array);
  13972. };
  13973. /**
  13974. * Set the value of an uniform to an array of int32 (stored as vec2)
  13975. * @param uniform defines the webGL uniform location where to store the value
  13976. * @param array defines the array of int32 to store
  13977. */
  13978. Engine.prototype.setIntArray2 = function (uniform, array) {
  13979. if (!uniform || array.length % 2 !== 0)
  13980. return;
  13981. this._gl.uniform2iv(uniform, array);
  13982. };
  13983. /**
  13984. * Set the value of an uniform to an array of int32 (stored as vec3)
  13985. * @param uniform defines the webGL uniform location where to store the value
  13986. * @param array defines the array of int32 to store
  13987. */
  13988. Engine.prototype.setIntArray3 = function (uniform, array) {
  13989. if (!uniform || array.length % 3 !== 0)
  13990. return;
  13991. this._gl.uniform3iv(uniform, array);
  13992. };
  13993. /**
  13994. * Set the value of an uniform to an array of int32 (stored as vec4)
  13995. * @param uniform defines the webGL uniform location where to store the value
  13996. * @param array defines the array of int32 to store
  13997. */
  13998. Engine.prototype.setIntArray4 = function (uniform, array) {
  13999. if (!uniform || array.length % 4 !== 0)
  14000. return;
  14001. this._gl.uniform4iv(uniform, array);
  14002. };
  14003. /**
  14004. * Set the value of an uniform to an array of float32
  14005. * @param uniform defines the webGL uniform location where to store the value
  14006. * @param array defines the array of float32 to store
  14007. */
  14008. Engine.prototype.setFloatArray = function (uniform, array) {
  14009. if (!uniform)
  14010. return;
  14011. this._gl.uniform1fv(uniform, array);
  14012. };
  14013. /**
  14014. * Set the value of an uniform to an array of float32 (stored as vec2)
  14015. * @param uniform defines the webGL uniform location where to store the value
  14016. * @param array defines the array of float32 to store
  14017. */
  14018. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14019. if (!uniform || array.length % 2 !== 0)
  14020. return;
  14021. this._gl.uniform2fv(uniform, array);
  14022. };
  14023. /**
  14024. * Set the value of an uniform to an array of float32 (stored as vec3)
  14025. * @param uniform defines the webGL uniform location where to store the value
  14026. * @param array defines the array of float32 to store
  14027. */
  14028. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14029. if (!uniform || array.length % 3 !== 0)
  14030. return;
  14031. this._gl.uniform3fv(uniform, array);
  14032. };
  14033. /**
  14034. * Set the value of an uniform to an array of float32 (stored as vec4)
  14035. * @param uniform defines the webGL uniform location where to store the value
  14036. * @param array defines the array of float32 to store
  14037. */
  14038. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14039. if (!uniform || array.length % 4 !== 0)
  14040. return;
  14041. this._gl.uniform4fv(uniform, array);
  14042. };
  14043. /**
  14044. * Set the value of an uniform to an array of number
  14045. * @param uniform defines the webGL uniform location where to store the value
  14046. * @param array defines the array of number to store
  14047. */
  14048. Engine.prototype.setArray = function (uniform, array) {
  14049. if (!uniform)
  14050. return;
  14051. this._gl.uniform1fv(uniform, array);
  14052. };
  14053. /**
  14054. * Set the value of an uniform to an array of number (stored as vec2)
  14055. * @param uniform defines the webGL uniform location where to store the value
  14056. * @param array defines the array of number to store
  14057. */
  14058. Engine.prototype.setArray2 = function (uniform, array) {
  14059. if (!uniform || array.length % 2 !== 0)
  14060. return;
  14061. this._gl.uniform2fv(uniform, array);
  14062. };
  14063. /**
  14064. * Set the value of an uniform to an array of number (stored as vec3)
  14065. * @param uniform defines the webGL uniform location where to store the value
  14066. * @param array defines the array of number to store
  14067. */
  14068. Engine.prototype.setArray3 = function (uniform, array) {
  14069. if (!uniform || array.length % 3 !== 0)
  14070. return;
  14071. this._gl.uniform3fv(uniform, array);
  14072. };
  14073. /**
  14074. * Set the value of an uniform to an array of number (stored as vec4)
  14075. * @param uniform defines the webGL uniform location where to store the value
  14076. * @param array defines the array of number to store
  14077. */
  14078. Engine.prototype.setArray4 = function (uniform, array) {
  14079. if (!uniform || array.length % 4 !== 0)
  14080. return;
  14081. this._gl.uniform4fv(uniform, array);
  14082. };
  14083. /**
  14084. * Set the value of an uniform to an array of float32 (stored as matrices)
  14085. * @param uniform defines the webGL uniform location where to store the value
  14086. * @param matrices defines the array of float32 to store
  14087. */
  14088. Engine.prototype.setMatrices = function (uniform, matrices) {
  14089. if (!uniform)
  14090. return;
  14091. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14092. };
  14093. /**
  14094. * Set the value of an uniform to a matrix
  14095. * @param uniform defines the webGL uniform location where to store the value
  14096. * @param matrix defines the matrix to store
  14097. */
  14098. Engine.prototype.setMatrix = function (uniform, matrix) {
  14099. if (!uniform)
  14100. return;
  14101. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14102. };
  14103. /**
  14104. * Set the value of an uniform to a matrix (3x3)
  14105. * @param uniform defines the webGL uniform location where to store the value
  14106. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14107. */
  14108. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14109. if (!uniform)
  14110. return;
  14111. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14112. };
  14113. /**
  14114. * Set the value of an uniform to a matrix (2x2)
  14115. * @param uniform defines the webGL uniform location where to store the value
  14116. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14117. */
  14118. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14119. if (!uniform)
  14120. return;
  14121. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14122. };
  14123. /**
  14124. * Set the value of an uniform to a number (int)
  14125. * @param uniform defines the webGL uniform location where to store the value
  14126. * @param value defines the int number to store
  14127. */
  14128. Engine.prototype.setInt = function (uniform, value) {
  14129. if (!uniform)
  14130. return;
  14131. this._gl.uniform1i(uniform, value);
  14132. };
  14133. /**
  14134. * Set the value of an uniform to a number (float)
  14135. * @param uniform defines the webGL uniform location where to store the value
  14136. * @param value defines the float number to store
  14137. */
  14138. Engine.prototype.setFloat = function (uniform, value) {
  14139. if (!uniform)
  14140. return;
  14141. this._gl.uniform1f(uniform, value);
  14142. };
  14143. /**
  14144. * Set the value of an uniform to a vec2
  14145. * @param uniform defines the webGL uniform location where to store the value
  14146. * @param x defines the 1st component of the value
  14147. * @param y defines the 2nd component of the value
  14148. */
  14149. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14150. if (!uniform)
  14151. return;
  14152. this._gl.uniform2f(uniform, x, y);
  14153. };
  14154. /**
  14155. * Set the value of an uniform to a vec3
  14156. * @param uniform defines the webGL uniform location where to store the value
  14157. * @param x defines the 1st component of the value
  14158. * @param y defines the 2nd component of the value
  14159. * @param z defines the 3rd component of the value
  14160. */
  14161. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14162. if (!uniform)
  14163. return;
  14164. this._gl.uniform3f(uniform, x, y, z);
  14165. };
  14166. /**
  14167. * Set the value of an uniform to a boolean
  14168. * @param uniform defines the webGL uniform location where to store the value
  14169. * @param bool defines the boolean to store
  14170. */
  14171. Engine.prototype.setBool = function (uniform, bool) {
  14172. if (!uniform)
  14173. return;
  14174. this._gl.uniform1i(uniform, bool);
  14175. };
  14176. /**
  14177. * Set the value of an uniform to a vec4
  14178. * @param uniform defines the webGL uniform location where to store the value
  14179. * @param x defines the 1st component of the value
  14180. * @param y defines the 2nd component of the value
  14181. * @param z defines the 3rd component of the value
  14182. * @param w defines the 4th component of the value
  14183. */
  14184. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14185. if (!uniform)
  14186. return;
  14187. this._gl.uniform4f(uniform, x, y, z, w);
  14188. };
  14189. /**
  14190. * Set the value of an uniform to a Color3
  14191. * @param uniform defines the webGL uniform location where to store the value
  14192. * @param color3 defines the color to store
  14193. */
  14194. Engine.prototype.setColor3 = function (uniform, color3) {
  14195. if (!uniform)
  14196. return;
  14197. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14198. };
  14199. /**
  14200. * Set the value of an uniform to a Color3 and an alpha value
  14201. * @param uniform defines the webGL uniform location where to store the value
  14202. * @param color3 defines the color to store
  14203. * @param alpha defines the alpha component to store
  14204. */
  14205. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14206. if (!uniform)
  14207. return;
  14208. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14209. };
  14210. /**
  14211. * Sets a Color4 on a uniform variable
  14212. * @param uniform defines the uniform location
  14213. * @param color4 defines the value to be set
  14214. */
  14215. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14216. if (!uniform)
  14217. return;
  14218. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14219. };
  14220. // States
  14221. /**
  14222. * Set various states to the webGL context
  14223. * @param culling defines backface culling state
  14224. * @param zOffset defines the value to apply to zOffset (0 by default)
  14225. * @param force defines if states must be applied even if cache is up to date
  14226. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14227. */
  14228. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14229. if (zOffset === void 0) { zOffset = 0; }
  14230. if (reverseSide === void 0) { reverseSide = false; }
  14231. // Culling
  14232. if (this._depthCullingState.cull !== culling || force) {
  14233. this._depthCullingState.cull = culling;
  14234. }
  14235. // Cull face
  14236. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14237. if (this._depthCullingState.cullFace !== cullFace || force) {
  14238. this._depthCullingState.cullFace = cullFace;
  14239. }
  14240. // Z offset
  14241. this.setZOffset(zOffset);
  14242. // Front face
  14243. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14244. if (this._depthCullingState.frontFace !== frontFace || force) {
  14245. this._depthCullingState.frontFace = frontFace;
  14246. }
  14247. };
  14248. /**
  14249. * Set the z offset to apply to current rendering
  14250. * @param value defines the offset to apply
  14251. */
  14252. Engine.prototype.setZOffset = function (value) {
  14253. this._depthCullingState.zOffset = value;
  14254. };
  14255. /**
  14256. * Gets the current value of the zOffset
  14257. * @returns the current zOffset state
  14258. */
  14259. Engine.prototype.getZOffset = function () {
  14260. return this._depthCullingState.zOffset;
  14261. };
  14262. /**
  14263. * Enable or disable depth buffering
  14264. * @param enable defines the state to set
  14265. */
  14266. Engine.prototype.setDepthBuffer = function (enable) {
  14267. this._depthCullingState.depthTest = enable;
  14268. };
  14269. /**
  14270. * Gets a boolean indicating if depth writing is enabled
  14271. * @returns the current depth writing state
  14272. */
  14273. Engine.prototype.getDepthWrite = function () {
  14274. return this._depthCullingState.depthMask;
  14275. };
  14276. /**
  14277. * Enable or disable depth writing
  14278. * @param enable defines the state to set
  14279. */
  14280. Engine.prototype.setDepthWrite = function (enable) {
  14281. this._depthCullingState.depthMask = enable;
  14282. };
  14283. /**
  14284. * Enable or disable color writing
  14285. * @param enable defines the state to set
  14286. */
  14287. Engine.prototype.setColorWrite = function (enable) {
  14288. this._gl.colorMask(enable, enable, enable, enable);
  14289. this._colorWrite = enable;
  14290. };
  14291. /**
  14292. * Gets a boolean indicating if color writing is enabled
  14293. * @returns the current color writing state
  14294. */
  14295. Engine.prototype.getColorWrite = function () {
  14296. return this._colorWrite;
  14297. };
  14298. /**
  14299. * Sets alpha constants used by some alpha blending modes
  14300. * @param r defines the red component
  14301. * @param g defines the green component
  14302. * @param b defines the blue component
  14303. * @param a defines the alpha component
  14304. */
  14305. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14306. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14307. };
  14308. /**
  14309. * Sets the current alpha mode
  14310. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14311. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14312. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14313. */
  14314. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14315. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14316. if (this._alphaMode === mode) {
  14317. return;
  14318. }
  14319. switch (mode) {
  14320. case Engine.ALPHA_DISABLE:
  14321. this._alphaState.alphaBlend = false;
  14322. break;
  14323. case Engine.ALPHA_PREMULTIPLIED:
  14324. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14325. this._alphaState.alphaBlend = true;
  14326. break;
  14327. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14328. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14329. this._alphaState.alphaBlend = true;
  14330. break;
  14331. case Engine.ALPHA_COMBINE:
  14332. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14333. this._alphaState.alphaBlend = true;
  14334. break;
  14335. case Engine.ALPHA_ONEONE:
  14336. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14337. this._alphaState.alphaBlend = true;
  14338. break;
  14339. case Engine.ALPHA_ADD:
  14340. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14341. this._alphaState.alphaBlend = true;
  14342. break;
  14343. case Engine.ALPHA_SUBTRACT:
  14344. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14345. this._alphaState.alphaBlend = true;
  14346. break;
  14347. case Engine.ALPHA_MULTIPLY:
  14348. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14349. this._alphaState.alphaBlend = true;
  14350. break;
  14351. case Engine.ALPHA_MAXIMIZED:
  14352. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14353. this._alphaState.alphaBlend = true;
  14354. break;
  14355. case Engine.ALPHA_INTERPOLATE:
  14356. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14357. this._alphaState.alphaBlend = true;
  14358. break;
  14359. case Engine.ALPHA_SCREENMODE:
  14360. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14361. this._alphaState.alphaBlend = true;
  14362. break;
  14363. }
  14364. if (!noDepthWriteChange) {
  14365. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14366. }
  14367. this._alphaMode = mode;
  14368. };
  14369. /**
  14370. * Gets the current alpha mode
  14371. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14372. * @returns the current alpha mode
  14373. */
  14374. Engine.prototype.getAlphaMode = function () {
  14375. return this._alphaMode;
  14376. };
  14377. // Textures
  14378. /**
  14379. * Force the entire cache to be cleared
  14380. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14381. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14382. */
  14383. Engine.prototype.wipeCaches = function (bruteForce) {
  14384. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14385. return;
  14386. }
  14387. this._currentEffect = null;
  14388. if (bruteForce) {
  14389. this.resetTextureCache();
  14390. this._currentProgram = null;
  14391. this._stencilState.reset();
  14392. this._depthCullingState.reset();
  14393. this.setDepthFunctionToLessOrEqual();
  14394. this._alphaState.reset();
  14395. }
  14396. this._resetVertexBufferBinding();
  14397. this._cachedIndexBuffer = null;
  14398. this._cachedEffectForVertexBuffers = null;
  14399. this._unbindVertexArrayObject();
  14400. this.bindIndexBuffer(null);
  14401. };
  14402. /**
  14403. * Set the compressed texture format to use, based on the formats you have, and the formats
  14404. * supported by the hardware / browser.
  14405. *
  14406. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14407. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14408. * to API arguments needed to compressed textures. This puts the burden on the container
  14409. * generator to house the arcane code for determining these for current & future formats.
  14410. *
  14411. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14412. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14413. *
  14414. * Note: The result of this call is not taken into account when a texture is base64.
  14415. *
  14416. * @param formatsAvailable defines the list of those format families you have created
  14417. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14418. *
  14419. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14420. * @returns The extension selected.
  14421. */
  14422. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14423. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14424. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14425. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14426. return this._textureFormatInUse = this._texturesSupported[i];
  14427. }
  14428. }
  14429. }
  14430. // actively set format to nothing, to allow this to be called more than once
  14431. // and possibly fail the 2nd time
  14432. this._textureFormatInUse = null;
  14433. return null;
  14434. };
  14435. /** @hidden */
  14436. Engine.prototype._createTexture = function () {
  14437. var texture = this._gl.createTexture();
  14438. if (!texture) {
  14439. throw new Error("Unable to create texture");
  14440. }
  14441. return texture;
  14442. };
  14443. /**
  14444. * Usually called from BABYLON.Texture.ts.
  14445. * Passed information to create a WebGLTexture
  14446. * @param urlArg defines a value which contains one of the following:
  14447. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14448. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14449. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14450. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14451. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14452. * @param scene needed for loading to the correct scene
  14453. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14454. * @param onLoad optional callback to be called upon successful completion
  14455. * @param onError optional callback to be called upon failure
  14456. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14457. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14458. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14459. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14460. */
  14461. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14462. var _this = this;
  14463. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14464. if (onLoad === void 0) { onLoad = null; }
  14465. if (onError === void 0) { onError = null; }
  14466. if (buffer === void 0) { buffer = null; }
  14467. if (fallback === void 0) { fallback = null; }
  14468. if (format === void 0) { format = null; }
  14469. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14470. var fromData = url.substr(0, 5) === "data:";
  14471. var fromBlob = url.substr(0, 5) === "blob:";
  14472. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14473. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14474. // establish the file extension, if possible
  14475. var lastDot = url.lastIndexOf('.');
  14476. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14477. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14478. var isTGA = (extension.indexOf(".tga") === 0);
  14479. // determine if a ktx file should be substituted
  14480. var isKTX = false;
  14481. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14482. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14483. isKTX = true;
  14484. }
  14485. if (scene) {
  14486. scene._addPendingData(texture);
  14487. }
  14488. texture.url = url;
  14489. texture.generateMipMaps = !noMipmap;
  14490. texture.samplingMode = samplingMode;
  14491. texture.invertY = invertY;
  14492. if (!this._doNotHandleContextLost) {
  14493. // Keep a link to the buffer only if we plan to handle context lost
  14494. texture._buffer = buffer;
  14495. }
  14496. var onLoadObserver = null;
  14497. if (onLoad && !fallback) {
  14498. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14499. }
  14500. if (!fallback)
  14501. this._internalTexturesCache.push(texture);
  14502. var onerror = function (message, exception) {
  14503. if (scene) {
  14504. scene._removePendingData(texture);
  14505. }
  14506. if (onLoadObserver) {
  14507. texture.onLoadedObservable.remove(onLoadObserver);
  14508. }
  14509. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14510. if (isKTX) {
  14511. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14512. }
  14513. else if (BABYLON.Tools.UseFallbackTexture) {
  14514. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14515. }
  14516. if (onError) {
  14517. onError(message || "Unknown error", exception);
  14518. }
  14519. };
  14520. var callback = null;
  14521. // processing for non-image formats
  14522. if (isKTX || isTGA || isDDS) {
  14523. if (isKTX) {
  14524. callback = function (data) {
  14525. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14526. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14527. ktx.uploadLevels(_this._gl, !noMipmap);
  14528. return false;
  14529. }, samplingMode);
  14530. };
  14531. }
  14532. else if (isTGA) {
  14533. callback = function (arrayBuffer) {
  14534. var data = new Uint8Array(arrayBuffer);
  14535. var header = BABYLON.TGATools.GetTGAHeader(data);
  14536. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14537. BABYLON.TGATools.UploadContent(_this._gl, data);
  14538. return false;
  14539. }, samplingMode);
  14540. };
  14541. }
  14542. else if (isDDS) {
  14543. callback = function (data) {
  14544. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14545. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14546. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14547. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14548. return false;
  14549. }, samplingMode);
  14550. };
  14551. }
  14552. if (!buffer) {
  14553. this._loadFile(url, function (data) {
  14554. if (callback) {
  14555. callback(data);
  14556. }
  14557. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14558. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14559. });
  14560. }
  14561. else {
  14562. if (callback) {
  14563. callback(buffer);
  14564. }
  14565. }
  14566. // image format processing
  14567. }
  14568. else {
  14569. var onload = function (img) {
  14570. if (fromBlob && !_this._doNotHandleContextLost) {
  14571. // We need to store the image if we need to rebuild the texture
  14572. // in case of a webgl context lost
  14573. texture._buffer = img;
  14574. }
  14575. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14576. var gl = _this._gl;
  14577. var isPot = (img.width === potWidth && img.height === potHeight);
  14578. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14579. if (isPot) {
  14580. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14581. return false;
  14582. }
  14583. // Using shaders to rescale because canvas.drawImage is lossy
  14584. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14585. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14586. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14587. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14588. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14589. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14590. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14591. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14592. _this._releaseTexture(source);
  14593. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14594. continuationCallback();
  14595. });
  14596. return true;
  14597. }, samplingMode);
  14598. };
  14599. if (!fromData || isBase64)
  14600. if (buffer instanceof HTMLImageElement) {
  14601. onload(buffer);
  14602. }
  14603. else {
  14604. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14605. }
  14606. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14607. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14608. else
  14609. onload(buffer);
  14610. }
  14611. return texture;
  14612. };
  14613. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14614. var _this = this;
  14615. var rtt = this.createRenderTargetTexture({
  14616. width: destination.width,
  14617. height: destination.height,
  14618. }, {
  14619. generateMipMaps: false,
  14620. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14621. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14622. generateDepthBuffer: false,
  14623. generateStencilBuffer: false
  14624. });
  14625. if (!this._rescalePostProcess) {
  14626. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14627. }
  14628. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14629. _this._rescalePostProcess.onApply = function (effect) {
  14630. effect._bindTexture("textureSampler", source);
  14631. };
  14632. var hostingScene = scene;
  14633. if (!hostingScene) {
  14634. hostingScene = _this.scenes[_this.scenes.length - 1];
  14635. }
  14636. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14637. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14638. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14639. _this.unBindFramebuffer(rtt);
  14640. _this._releaseTexture(rtt);
  14641. if (onComplete) {
  14642. onComplete();
  14643. }
  14644. });
  14645. };
  14646. /**
  14647. * Update a raw texture
  14648. * @param texture defines the texture to update
  14649. * @param data defines the data to store in the texture
  14650. * @param format defines the format of the data
  14651. * @param invertY defines if data must be stored with Y axis inverted
  14652. * @param compression defines the compression used (null by default)
  14653. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14654. */
  14655. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14656. if (compression === void 0) { compression = null; }
  14657. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14658. if (!texture) {
  14659. return;
  14660. }
  14661. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14662. var internalFormat = this._getInternalFormat(format);
  14663. var textureType = this._getWebGLTextureType(type);
  14664. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14665. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14666. if (!this._doNotHandleContextLost) {
  14667. texture._bufferView = data;
  14668. texture.format = format;
  14669. texture.type = type;
  14670. texture.invertY = invertY;
  14671. texture._compression = compression;
  14672. }
  14673. if (texture.width % 4 !== 0) {
  14674. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14675. }
  14676. if (compression && data) {
  14677. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14678. }
  14679. else {
  14680. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14681. }
  14682. if (texture.generateMipMaps) {
  14683. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14684. }
  14685. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14686. // this.resetTextureCache();
  14687. texture.isReady = true;
  14688. };
  14689. /**
  14690. * Creates a raw texture
  14691. * @param data defines the data to store in the texture
  14692. * @param width defines the width of the texture
  14693. * @param height defines the height of the texture
  14694. * @param format defines the format of the data
  14695. * @param generateMipMaps defines if the engine should generate the mip levels
  14696. * @param invertY defines if data must be stored with Y axis inverted
  14697. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14698. * @param compression defines the compression used (null by default)
  14699. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14700. * @returns the raw texture inside an InternalTexture
  14701. */
  14702. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14703. if (compression === void 0) { compression = null; }
  14704. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14705. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14706. texture.baseWidth = width;
  14707. texture.baseHeight = height;
  14708. texture.width = width;
  14709. texture.height = height;
  14710. texture.format = format;
  14711. texture.generateMipMaps = generateMipMaps;
  14712. texture.samplingMode = samplingMode;
  14713. texture.invertY = invertY;
  14714. texture._compression = compression;
  14715. texture.type = type;
  14716. if (!this._doNotHandleContextLost) {
  14717. texture._bufferView = data;
  14718. }
  14719. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14720. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14721. // Filters
  14722. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14723. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14724. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14725. if (generateMipMaps) {
  14726. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14727. }
  14728. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14729. this._internalTexturesCache.push(texture);
  14730. return texture;
  14731. };
  14732. /**
  14733. * Creates a dynamic texture
  14734. * @param width defines the width of the texture
  14735. * @param height defines the height of the texture
  14736. * @param generateMipMaps defines if the engine should generate the mip levels
  14737. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14738. * @returns the dynamic texture inside an InternalTexture
  14739. */
  14740. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14741. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14742. texture.baseWidth = width;
  14743. texture.baseHeight = height;
  14744. if (generateMipMaps) {
  14745. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14746. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14747. }
  14748. // this.resetTextureCache();
  14749. texture.width = width;
  14750. texture.height = height;
  14751. texture.isReady = false;
  14752. texture.generateMipMaps = generateMipMaps;
  14753. texture.samplingMode = samplingMode;
  14754. this.updateTextureSamplingMode(samplingMode, texture);
  14755. this._internalTexturesCache.push(texture);
  14756. return texture;
  14757. };
  14758. /**
  14759. * Update the sampling mode of a given texture
  14760. * @param samplingMode defines the required sampling mode
  14761. * @param texture defines the texture to update
  14762. */
  14763. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14764. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14765. if (texture.isCube) {
  14766. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14767. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14768. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14769. }
  14770. else if (texture.is3D) {
  14771. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14772. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14773. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14774. }
  14775. else {
  14776. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14777. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14778. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14779. }
  14780. texture.samplingMode = samplingMode;
  14781. };
  14782. /**
  14783. * Update the content of a dynamic texture
  14784. * @param texture defines the texture to update
  14785. * @param canvas defines the canvas containing the source
  14786. * @param invertY defines if data must be stored with Y axis inverted
  14787. * @param premulAlpha defines if alpha is stored as premultiplied
  14788. * @param format defines the format of the data
  14789. */
  14790. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14791. if (premulAlpha === void 0) { premulAlpha = false; }
  14792. if (!texture) {
  14793. return;
  14794. }
  14795. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14796. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14797. if (premulAlpha) {
  14798. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14799. }
  14800. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14801. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14802. if (texture.generateMipMaps) {
  14803. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14804. }
  14805. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14806. if (premulAlpha) {
  14807. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14808. }
  14809. texture.isReady = true;
  14810. };
  14811. /**
  14812. * Update a video texture
  14813. * @param texture defines the texture to update
  14814. * @param video defines the video element to use
  14815. * @param invertY defines if data must be stored with Y axis inverted
  14816. */
  14817. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14818. if (!texture || texture._isDisabled) {
  14819. return;
  14820. }
  14821. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14822. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14823. try {
  14824. // Testing video texture support
  14825. if (this._videoTextureSupported === undefined) {
  14826. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14827. if (this._gl.getError() !== 0) {
  14828. this._videoTextureSupported = false;
  14829. }
  14830. else {
  14831. this._videoTextureSupported = true;
  14832. }
  14833. }
  14834. // Copy video through the current working canvas if video texture is not supported
  14835. if (!this._videoTextureSupported) {
  14836. if (!texture._workingCanvas) {
  14837. texture._workingCanvas = document.createElement("canvas");
  14838. var context = texture._workingCanvas.getContext("2d");
  14839. if (!context) {
  14840. throw new Error("Unable to get 2d context");
  14841. }
  14842. texture._workingContext = context;
  14843. texture._workingCanvas.width = texture.width;
  14844. texture._workingCanvas.height = texture.height;
  14845. }
  14846. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14847. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14848. }
  14849. else {
  14850. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14851. }
  14852. if (texture.generateMipMaps) {
  14853. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14854. }
  14855. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14856. // this.resetTextureCache();
  14857. texture.isReady = true;
  14858. }
  14859. catch (ex) {
  14860. // Something unexpected
  14861. // Let's disable the texture
  14862. texture._isDisabled = true;
  14863. }
  14864. };
  14865. /**
  14866. * Updates a depth texture Comparison Mode and Function.
  14867. * If the comparison Function is equal to 0, the mode will be set to none.
  14868. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14869. * @param texture The texture to set the comparison function for
  14870. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14871. */
  14872. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14873. if (this.webGLVersion === 1) {
  14874. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14875. return;
  14876. }
  14877. var gl = this._gl;
  14878. if (texture.isCube) {
  14879. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14880. if (comparisonFunction === 0) {
  14881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14883. }
  14884. else {
  14885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14887. }
  14888. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14889. }
  14890. else {
  14891. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14892. if (comparisonFunction === 0) {
  14893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14895. }
  14896. else {
  14897. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14898. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14899. }
  14900. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14901. }
  14902. texture._comparisonFunction = comparisonFunction;
  14903. };
  14904. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14905. var width = size.width || size;
  14906. var height = size.height || size;
  14907. internalTexture.baseWidth = width;
  14908. internalTexture.baseHeight = height;
  14909. internalTexture.width = width;
  14910. internalTexture.height = height;
  14911. internalTexture.isReady = true;
  14912. internalTexture.samples = 1;
  14913. internalTexture.generateMipMaps = false;
  14914. internalTexture._generateDepthBuffer = true;
  14915. internalTexture._generateStencilBuffer = generateStencil;
  14916. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14917. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14918. internalTexture._comparisonFunction = comparisonFunction;
  14919. var gl = this._gl;
  14920. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14921. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14922. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14923. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14924. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14925. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14926. if (comparisonFunction === 0) {
  14927. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14928. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14929. }
  14930. else {
  14931. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14932. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14933. }
  14934. };
  14935. /**
  14936. * Creates a depth stencil texture.
  14937. * This is only available in WebGL 2 or with the depth texture extension available.
  14938. * @param size The size of face edge in the texture.
  14939. * @param options The options defining the texture.
  14940. * @returns The texture
  14941. */
  14942. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14943. if (options.isCube) {
  14944. var width = size.width || size;
  14945. return this._createDepthStencilCubeTexture(width, options);
  14946. }
  14947. else {
  14948. return this._createDepthStencilTexture(size, options);
  14949. }
  14950. };
  14951. /**
  14952. * Creates a depth stencil texture.
  14953. * This is only available in WebGL 2 or with the depth texture extension available.
  14954. * @param size The size of face edge in the texture.
  14955. * @param options The options defining the texture.
  14956. * @returns The texture
  14957. */
  14958. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14959. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14960. if (!this._caps.depthTextureExtension) {
  14961. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14962. return internalTexture;
  14963. }
  14964. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14965. var gl = this._gl;
  14966. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14967. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14968. if (this.webGLVersion > 1) {
  14969. if (internalOptions.generateStencil) {
  14970. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14971. }
  14972. else {
  14973. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14974. }
  14975. }
  14976. else {
  14977. if (internalOptions.generateStencil) {
  14978. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14979. }
  14980. else {
  14981. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14982. }
  14983. }
  14984. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14985. return internalTexture;
  14986. };
  14987. /**
  14988. * Creates a depth stencil cube texture.
  14989. * This is only available in WebGL 2.
  14990. * @param size The size of face edge in the cube texture.
  14991. * @param options The options defining the cube texture.
  14992. * @returns The cube texture
  14993. */
  14994. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14995. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14996. internalTexture.isCube = true;
  14997. if (this.webGLVersion === 1) {
  14998. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14999. return internalTexture;
  15000. }
  15001. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15002. var gl = this._gl;
  15003. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15004. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15005. // Create the depth/stencil buffer
  15006. for (var face = 0; face < 6; face++) {
  15007. if (internalOptions.generateStencil) {
  15008. 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);
  15009. }
  15010. else {
  15011. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15012. }
  15013. }
  15014. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15015. return internalTexture;
  15016. };
  15017. /**
  15018. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15019. * @param renderTarget The render target to set the frame buffer for
  15020. */
  15021. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15022. // Create the framebuffer
  15023. var internalTexture = renderTarget.getInternalTexture();
  15024. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15025. return;
  15026. }
  15027. var gl = this._gl;
  15028. var depthStencilTexture = renderTarget.depthStencilTexture;
  15029. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15030. if (depthStencilTexture.isCube) {
  15031. if (depthStencilTexture._generateStencilBuffer) {
  15032. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15033. }
  15034. else {
  15035. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15036. }
  15037. }
  15038. else {
  15039. if (depthStencilTexture._generateStencilBuffer) {
  15040. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15041. }
  15042. else {
  15043. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15044. }
  15045. }
  15046. this.bindUnboundFramebuffer(null);
  15047. };
  15048. /**
  15049. * Creates a new render target texture
  15050. * @param size defines the size of the texture
  15051. * @param options defines the options used to create the texture
  15052. * @returns a new render target texture stored in an InternalTexture
  15053. */
  15054. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15055. var fullOptions = new RenderTargetCreationOptions();
  15056. if (options !== undefined && typeof options === "object") {
  15057. fullOptions.generateMipMaps = options.generateMipMaps;
  15058. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15059. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15060. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15061. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15062. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15063. }
  15064. else {
  15065. fullOptions.generateMipMaps = options;
  15066. fullOptions.generateDepthBuffer = true;
  15067. fullOptions.generateStencilBuffer = false;
  15068. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15069. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15070. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15071. }
  15072. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15073. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15074. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15075. }
  15076. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15077. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15078. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15079. }
  15080. var gl = this._gl;
  15081. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15082. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15083. var width = size.width || size;
  15084. var height = size.height || size;
  15085. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15086. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15087. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15088. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15089. }
  15090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15093. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15094. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15095. // Create the framebuffer
  15096. var framebuffer = gl.createFramebuffer();
  15097. this.bindUnboundFramebuffer(framebuffer);
  15098. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15099. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15100. if (fullOptions.generateMipMaps) {
  15101. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15102. }
  15103. // Unbind
  15104. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15105. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15106. this.bindUnboundFramebuffer(null);
  15107. texture._framebuffer = framebuffer;
  15108. texture.baseWidth = width;
  15109. texture.baseHeight = height;
  15110. texture.width = width;
  15111. texture.height = height;
  15112. texture.isReady = true;
  15113. texture.samples = 1;
  15114. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15115. texture.samplingMode = fullOptions.samplingMode;
  15116. texture.type = fullOptions.type;
  15117. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15118. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15119. // this.resetTextureCache();
  15120. this._internalTexturesCache.push(texture);
  15121. return texture;
  15122. };
  15123. /**
  15124. * Create a multi render target texture
  15125. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15126. * @param size defines the size of the texture
  15127. * @param options defines the creation options
  15128. * @returns the cube texture as an InternalTexture
  15129. */
  15130. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15131. var generateMipMaps = false;
  15132. var generateDepthBuffer = true;
  15133. var generateStencilBuffer = false;
  15134. var generateDepthTexture = false;
  15135. var textureCount = 1;
  15136. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15137. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15138. var types = new Array();
  15139. var samplingModes = new Array();
  15140. if (options !== undefined) {
  15141. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15142. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15143. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15144. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15145. textureCount = options.textureCount || 1;
  15146. if (options.types) {
  15147. types = options.types;
  15148. }
  15149. if (options.samplingModes) {
  15150. samplingModes = options.samplingModes;
  15151. }
  15152. }
  15153. var gl = this._gl;
  15154. // Create the framebuffer
  15155. var framebuffer = gl.createFramebuffer();
  15156. this.bindUnboundFramebuffer(framebuffer);
  15157. var width = size.width || size;
  15158. var height = size.height || size;
  15159. var textures = [];
  15160. var attachments = [];
  15161. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15162. for (var i = 0; i < textureCount; i++) {
  15163. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15164. var type = types[i] || defaultType;
  15165. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15166. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15167. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15168. }
  15169. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15170. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15171. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15172. }
  15173. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15174. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15175. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15176. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15177. }
  15178. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15179. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15180. textures.push(texture);
  15181. attachments.push(attachment);
  15182. gl.activeTexture(gl["TEXTURE" + i]);
  15183. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15184. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15185. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15186. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15188. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15189. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15190. if (generateMipMaps) {
  15191. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15192. }
  15193. // Unbind
  15194. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15195. texture._framebuffer = framebuffer;
  15196. texture._depthStencilBuffer = depthStencilBuffer;
  15197. texture.baseWidth = width;
  15198. texture.baseHeight = height;
  15199. texture.width = width;
  15200. texture.height = height;
  15201. texture.isReady = true;
  15202. texture.samples = 1;
  15203. texture.generateMipMaps = generateMipMaps;
  15204. texture.samplingMode = samplingMode;
  15205. texture.type = type;
  15206. texture._generateDepthBuffer = generateDepthBuffer;
  15207. texture._generateStencilBuffer = generateStencilBuffer;
  15208. texture._attachments = attachments;
  15209. this._internalTexturesCache.push(texture);
  15210. }
  15211. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15212. // Depth texture
  15213. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15214. gl.activeTexture(gl.TEXTURE0);
  15215. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15216. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15220. 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);
  15221. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15222. depthTexture._framebuffer = framebuffer;
  15223. depthTexture.baseWidth = width;
  15224. depthTexture.baseHeight = height;
  15225. depthTexture.width = width;
  15226. depthTexture.height = height;
  15227. depthTexture.isReady = true;
  15228. depthTexture.samples = 1;
  15229. depthTexture.generateMipMaps = generateMipMaps;
  15230. depthTexture.samplingMode = gl.NEAREST;
  15231. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15232. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15233. textures.push(depthTexture);
  15234. this._internalTexturesCache.push(depthTexture);
  15235. }
  15236. gl.drawBuffers(attachments);
  15237. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15238. this.bindUnboundFramebuffer(null);
  15239. this.resetTextureCache();
  15240. return textures;
  15241. };
  15242. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15243. if (samples === void 0) { samples = 1; }
  15244. var depthStencilBuffer = null;
  15245. var gl = this._gl;
  15246. // Create the depth/stencil buffer
  15247. if (generateStencilBuffer) {
  15248. depthStencilBuffer = gl.createRenderbuffer();
  15249. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15250. if (samples > 1) {
  15251. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15252. }
  15253. else {
  15254. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15255. }
  15256. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15257. }
  15258. else if (generateDepthBuffer) {
  15259. depthStencilBuffer = gl.createRenderbuffer();
  15260. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15261. if (samples > 1) {
  15262. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15263. }
  15264. else {
  15265. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15266. }
  15267. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15268. }
  15269. return depthStencilBuffer;
  15270. };
  15271. /**
  15272. * Updates the sample count of a render target texture
  15273. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15274. * @param texture defines the texture to update
  15275. * @param samples defines the sample count to set
  15276. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15277. */
  15278. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15279. if (this.webGLVersion < 2 || !texture) {
  15280. return 1;
  15281. }
  15282. if (texture.samples === samples) {
  15283. return samples;
  15284. }
  15285. var gl = this._gl;
  15286. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15287. // Dispose previous render buffers
  15288. if (texture._depthStencilBuffer) {
  15289. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15290. texture._depthStencilBuffer = null;
  15291. }
  15292. if (texture._MSAAFramebuffer) {
  15293. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15294. texture._MSAAFramebuffer = null;
  15295. }
  15296. if (texture._MSAARenderBuffer) {
  15297. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15298. texture._MSAARenderBuffer = null;
  15299. }
  15300. if (samples > 1) {
  15301. var framebuffer = gl.createFramebuffer();
  15302. if (!framebuffer) {
  15303. throw new Error("Unable to create multi sampled framebuffer");
  15304. }
  15305. texture._MSAAFramebuffer = framebuffer;
  15306. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15307. var colorRenderbuffer = gl.createRenderbuffer();
  15308. if (!colorRenderbuffer) {
  15309. throw new Error("Unable to create multi sampled framebuffer");
  15310. }
  15311. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15312. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15313. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15314. texture._MSAARenderBuffer = colorRenderbuffer;
  15315. }
  15316. else {
  15317. this.bindUnboundFramebuffer(texture._framebuffer);
  15318. }
  15319. texture.samples = samples;
  15320. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15321. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15322. this.bindUnboundFramebuffer(null);
  15323. return samples;
  15324. };
  15325. /**
  15326. * Update the sample count for a given multiple render target texture
  15327. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15328. * @param textures defines the textures to update
  15329. * @param samples defines the sample count to set
  15330. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15331. */
  15332. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15333. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15334. return 1;
  15335. }
  15336. if (textures[0].samples === samples) {
  15337. return samples;
  15338. }
  15339. var gl = this._gl;
  15340. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15341. // Dispose previous render buffers
  15342. if (textures[0]._depthStencilBuffer) {
  15343. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15344. textures[0]._depthStencilBuffer = null;
  15345. }
  15346. if (textures[0]._MSAAFramebuffer) {
  15347. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15348. textures[0]._MSAAFramebuffer = null;
  15349. }
  15350. for (var i = 0; i < textures.length; i++) {
  15351. if (textures[i]._MSAARenderBuffer) {
  15352. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15353. textures[i]._MSAARenderBuffer = null;
  15354. }
  15355. }
  15356. if (samples > 1) {
  15357. var framebuffer = gl.createFramebuffer();
  15358. if (!framebuffer) {
  15359. throw new Error("Unable to create multi sampled framebuffer");
  15360. }
  15361. this.bindUnboundFramebuffer(framebuffer);
  15362. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15363. var attachments = [];
  15364. for (var i = 0; i < textures.length; i++) {
  15365. var texture = textures[i];
  15366. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15367. var colorRenderbuffer = gl.createRenderbuffer();
  15368. if (!colorRenderbuffer) {
  15369. throw new Error("Unable to create multi sampled framebuffer");
  15370. }
  15371. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15372. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15373. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15374. texture._MSAAFramebuffer = framebuffer;
  15375. texture._MSAARenderBuffer = colorRenderbuffer;
  15376. texture.samples = samples;
  15377. texture._depthStencilBuffer = depthStencilBuffer;
  15378. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15379. attachments.push(attachment);
  15380. }
  15381. gl.drawBuffers(attachments);
  15382. }
  15383. else {
  15384. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15385. }
  15386. this.bindUnboundFramebuffer(null);
  15387. return samples;
  15388. };
  15389. /** @hidden */
  15390. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15391. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15392. };
  15393. /** @hidden */
  15394. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15395. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15396. };
  15397. /**
  15398. * Creates a new render target cube texture
  15399. * @param size defines the size of the texture
  15400. * @param options defines the options used to create the texture
  15401. * @returns a new render target cube texture stored in an InternalTexture
  15402. */
  15403. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15404. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15405. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15406. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15407. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15408. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15409. }
  15410. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15411. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15412. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15413. }
  15414. var gl = this._gl;
  15415. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15416. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15417. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15418. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15419. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15420. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15421. }
  15422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15424. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15425. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15426. for (var face = 0; face < 6; face++) {
  15427. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15428. }
  15429. // Create the framebuffer
  15430. var framebuffer = gl.createFramebuffer();
  15431. this.bindUnboundFramebuffer(framebuffer);
  15432. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15433. // MipMaps
  15434. if (fullOptions.generateMipMaps) {
  15435. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15436. }
  15437. // Unbind
  15438. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15439. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15440. this.bindUnboundFramebuffer(null);
  15441. texture._framebuffer = framebuffer;
  15442. texture.width = size;
  15443. texture.height = size;
  15444. texture.isReady = true;
  15445. texture.isCube = true;
  15446. texture.samples = 1;
  15447. texture.generateMipMaps = fullOptions.generateMipMaps;
  15448. texture.samplingMode = fullOptions.samplingMode;
  15449. texture.type = fullOptions.type;
  15450. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15451. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15452. this._internalTexturesCache.push(texture);
  15453. return texture;
  15454. };
  15455. /**
  15456. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15457. * @param rootUrl defines the url where the file to load is located
  15458. * @param scene defines the current scene
  15459. * @param scale defines scale to apply to the mip map selection
  15460. * @param offset defines offset to apply to the mip map selection
  15461. * @param onLoad defines an optional callback raised when the texture is loaded
  15462. * @param onError defines an optional callback raised if there is an issue to load the texture
  15463. * @param format defines the format of the data
  15464. * @param forcedExtension defines the extension to use to pick the right loader
  15465. * @returns the cube texture as an InternalTexture
  15466. */
  15467. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15468. var _this = this;
  15469. if (onLoad === void 0) { onLoad = null; }
  15470. if (onError === void 0) { onError = null; }
  15471. if (forcedExtension === void 0) { forcedExtension = null; }
  15472. var callback = function (loadData) {
  15473. if (!loadData) {
  15474. if (onLoad) {
  15475. onLoad(null);
  15476. }
  15477. return;
  15478. }
  15479. var texture = loadData.texture;
  15480. if (loadData.info.sphericalPolynomial) {
  15481. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15482. }
  15483. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15484. texture._lodGenerationScale = scale;
  15485. texture._lodGenerationOffset = offset;
  15486. if (_this._caps.textureLOD) {
  15487. // Do not add extra process if texture lod is supported.
  15488. if (onLoad) {
  15489. onLoad(texture);
  15490. }
  15491. return;
  15492. }
  15493. var mipSlices = 3;
  15494. var gl = _this._gl;
  15495. var width = loadData.width;
  15496. if (!width) {
  15497. return;
  15498. }
  15499. var textures = [];
  15500. for (var i = 0; i < mipSlices; i++) {
  15501. //compute LOD from even spacing in smoothness (matching shader calculation)
  15502. var smoothness = i / (mipSlices - 1);
  15503. var roughness = 1 - smoothness;
  15504. var minLODIndex = offset; // roughness = 0
  15505. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15506. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15507. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15508. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15509. glTextureFromLod.isCube = true;
  15510. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15511. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15512. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15513. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15515. if (loadData.isDDS) {
  15516. var info = loadData.info;
  15517. var data = loadData.data;
  15518. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15519. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15520. }
  15521. else {
  15522. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15523. }
  15524. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15525. // Wrap in a base texture for easy binding.
  15526. var lodTexture = new BABYLON.BaseTexture(scene);
  15527. lodTexture.isCube = true;
  15528. lodTexture._texture = glTextureFromLod;
  15529. glTextureFromLod.isReady = true;
  15530. textures.push(lodTexture);
  15531. }
  15532. texture._lodTextureHigh = textures[2];
  15533. texture._lodTextureMid = textures[1];
  15534. texture._lodTextureLow = textures[0];
  15535. if (onLoad) {
  15536. onLoad(texture);
  15537. }
  15538. };
  15539. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15540. };
  15541. /**
  15542. * Creates a cube texture
  15543. * @param rootUrl defines the url where the files to load is located
  15544. * @param scene defines the current scene
  15545. * @param files defines the list of files to load (1 per face)
  15546. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15547. * @param onLoad defines an optional callback raised when the texture is loaded
  15548. * @param onError defines an optional callback raised if there is an issue to load the texture
  15549. * @param format defines the format of the data
  15550. * @param forcedExtension defines the extension to use to pick the right loader
  15551. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15552. * @returns the cube texture as an InternalTexture
  15553. */
  15554. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15555. var _this = this;
  15556. if (onLoad === void 0) { onLoad = null; }
  15557. if (onError === void 0) { onError = null; }
  15558. if (forcedExtension === void 0) { forcedExtension = null; }
  15559. if (createPolynomials === void 0) { createPolynomials = false; }
  15560. var gl = this._gl;
  15561. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15562. texture.isCube = true;
  15563. texture.url = rootUrl;
  15564. texture.generateMipMaps = !noMipmap;
  15565. if (!this._doNotHandleContextLost) {
  15566. texture._extension = forcedExtension;
  15567. texture._files = files;
  15568. }
  15569. var isKTX = false;
  15570. var isDDS = false;
  15571. var lastDot = rootUrl.lastIndexOf('.');
  15572. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15573. if (this._textureFormatInUse) {
  15574. extension = this._textureFormatInUse;
  15575. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15576. isKTX = true;
  15577. }
  15578. else {
  15579. isDDS = (extension === ".dds");
  15580. }
  15581. var onerror = function (request, exception) {
  15582. if (onError && request) {
  15583. onError(request.status + " " + request.statusText, exception);
  15584. }
  15585. };
  15586. if (isKTX) {
  15587. this._loadFile(rootUrl, function (data) {
  15588. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15589. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15590. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15591. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15592. ktx.uploadLevels(_this._gl, !noMipmap);
  15593. _this.setCubeMapTextureParams(gl, loadMipmap);
  15594. texture.width = ktx.pixelWidth;
  15595. texture.height = ktx.pixelHeight;
  15596. texture.isReady = true;
  15597. }, undefined, undefined, true, onerror);
  15598. }
  15599. else if (isDDS) {
  15600. if (files && files.length === 6) {
  15601. this._cascadeLoadFiles(scene, function (imgs) {
  15602. var info;
  15603. var loadMipmap = false;
  15604. var width = 0;
  15605. for (var index = 0; index < imgs.length; index++) {
  15606. var data = imgs[index];
  15607. info = BABYLON.DDSTools.GetDDSInfo(data);
  15608. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15609. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15610. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15611. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15612. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15613. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15614. }
  15615. texture.width = info.width;
  15616. texture.height = info.height;
  15617. texture.type = info.textureType;
  15618. width = info.width;
  15619. }
  15620. _this.setCubeMapTextureParams(gl, loadMipmap);
  15621. texture.isReady = true;
  15622. if (onLoad) {
  15623. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15624. }
  15625. }, files, onError);
  15626. }
  15627. else {
  15628. this._loadFile(rootUrl, function (data) {
  15629. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15630. if (createPolynomials) {
  15631. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15632. }
  15633. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15634. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15635. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15636. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15637. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15638. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15639. }
  15640. _this.setCubeMapTextureParams(gl, loadMipmap);
  15641. texture.width = info.width;
  15642. texture.height = info.height;
  15643. texture.isReady = true;
  15644. texture.type = info.textureType;
  15645. if (onLoad) {
  15646. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15647. }
  15648. }, undefined, undefined, true, onerror);
  15649. }
  15650. }
  15651. else {
  15652. if (!files) {
  15653. throw new Error("Cannot load cubemap because files were not defined");
  15654. }
  15655. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15656. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15657. var height = width;
  15658. _this._prepareWorkingCanvas();
  15659. if (!_this._workingCanvas || !_this._workingContext) {
  15660. return;
  15661. }
  15662. _this._workingCanvas.width = width;
  15663. _this._workingCanvas.height = height;
  15664. var faces = [
  15665. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15666. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15667. ];
  15668. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15669. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15670. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15671. for (var index = 0; index < faces.length; index++) {
  15672. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15673. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15674. }
  15675. if (!noMipmap) {
  15676. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15677. }
  15678. _this.setCubeMapTextureParams(gl, !noMipmap);
  15679. texture.width = width;
  15680. texture.height = height;
  15681. texture.isReady = true;
  15682. if (format) {
  15683. texture.format = format;
  15684. }
  15685. texture.onLoadedObservable.notifyObservers(texture);
  15686. texture.onLoadedObservable.clear();
  15687. if (onLoad) {
  15688. onLoad();
  15689. }
  15690. }, files, onError);
  15691. }
  15692. this._internalTexturesCache.push(texture);
  15693. return texture;
  15694. };
  15695. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15696. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15697. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15698. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15700. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15701. // this.resetTextureCache();
  15702. };
  15703. /**
  15704. * Update a raw cube texture
  15705. * @param texture defines the texture to udpdate
  15706. * @param data defines the data to store
  15707. * @param format defines the data format
  15708. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15709. * @param invertY defines if data must be stored with Y axis inverted
  15710. * @param compression defines the compression used (null by default)
  15711. * @param level defines which level of the texture to update
  15712. */
  15713. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15714. if (compression === void 0) { compression = null; }
  15715. if (level === void 0) { level = 0; }
  15716. texture._bufferViewArray = data;
  15717. texture.format = format;
  15718. texture.type = type;
  15719. texture.invertY = invertY;
  15720. texture._compression = compression;
  15721. var gl = this._gl;
  15722. var textureType = this._getWebGLTextureType(type);
  15723. var internalFormat = this._getInternalFormat(format);
  15724. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15725. var needConversion = false;
  15726. if (internalFormat === gl.RGB) {
  15727. internalFormat = gl.RGBA;
  15728. needConversion = true;
  15729. }
  15730. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15731. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15732. if (texture.width % 4 !== 0) {
  15733. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15734. }
  15735. // Data are known to be in +X +Y +Z -X -Y -Z
  15736. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15737. var faceData = data[faceIndex];
  15738. if (compression) {
  15739. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15740. }
  15741. else {
  15742. if (needConversion) {
  15743. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15744. }
  15745. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15746. }
  15747. }
  15748. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15749. if (isPot && texture.generateMipMaps && level === 0) {
  15750. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15751. }
  15752. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15753. // this.resetTextureCache();
  15754. texture.isReady = true;
  15755. };
  15756. /**
  15757. * Creates a new raw cube texture
  15758. * @param data defines the array of data to use to create each face
  15759. * @param size defines the size of the textures
  15760. * @param format defines the format of the data
  15761. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15762. * @param generateMipMaps defines if the engine should generate the mip levels
  15763. * @param invertY defines if data must be stored with Y axis inverted
  15764. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15765. * @param compression defines the compression used (null by default)
  15766. * @returns the cube texture as an InternalTexture
  15767. */
  15768. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15769. if (compression === void 0) { compression = null; }
  15770. var gl = this._gl;
  15771. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15772. texture.isCube = true;
  15773. texture.generateMipMaps = generateMipMaps;
  15774. texture.format = format;
  15775. texture.type = type;
  15776. if (!this._doNotHandleContextLost) {
  15777. texture._bufferViewArray = data;
  15778. }
  15779. var textureType = this._getWebGLTextureType(type);
  15780. var internalFormat = this._getInternalFormat(format);
  15781. if (internalFormat === gl.RGB) {
  15782. internalFormat = gl.RGBA;
  15783. }
  15784. var width = size;
  15785. var height = width;
  15786. texture.width = width;
  15787. texture.height = height;
  15788. // Double check on POT to generate Mips.
  15789. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15790. if (!isPot) {
  15791. generateMipMaps = false;
  15792. }
  15793. // Upload data if needed. The texture won't be ready until then.
  15794. if (data) {
  15795. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15796. }
  15797. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15798. // Filters
  15799. if (data && generateMipMaps) {
  15800. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15801. }
  15802. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15804. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15805. }
  15806. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15809. }
  15810. else {
  15811. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15812. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15813. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15814. }
  15815. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15816. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15817. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15818. return texture;
  15819. };
  15820. /**
  15821. * Creates a new raw cube texture from a specified url
  15822. * @param url defines the url where the data is located
  15823. * @param scene defines the current scene
  15824. * @param size defines the size of the textures
  15825. * @param format defines the format of the data
  15826. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15827. * @param noMipmap defines if the engine should avoid generating the mip levels
  15828. * @param callback defines a callback used to extract texture data from loaded data
  15829. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15830. * @param onLoad defines a callback called when texture is loaded
  15831. * @param onError defines a callback called if there is an error
  15832. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15833. * @param invertY defines if data must be stored with Y axis inverted
  15834. * @returns the cube texture as an InternalTexture
  15835. */
  15836. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15837. var _this = this;
  15838. if (onLoad === void 0) { onLoad = null; }
  15839. if (onError === void 0) { onError = null; }
  15840. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15841. if (invertY === void 0) { invertY = false; }
  15842. var gl = this._gl;
  15843. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15844. scene._addPendingData(texture);
  15845. texture.url = url;
  15846. this._internalTexturesCache.push(texture);
  15847. var onerror = function (request, exception) {
  15848. scene._removePendingData(texture);
  15849. if (onError && request) {
  15850. onError(request.status + " " + request.statusText, exception);
  15851. }
  15852. };
  15853. var internalCallback = function (data) {
  15854. var width = texture.width;
  15855. var faceDataArrays = callback(data);
  15856. if (!faceDataArrays) {
  15857. return;
  15858. }
  15859. if (mipmapGenerator) {
  15860. var textureType = _this._getWebGLTextureType(type);
  15861. var internalFormat = _this._getInternalFormat(format);
  15862. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15863. var needConversion = false;
  15864. if (internalFormat === gl.RGB) {
  15865. internalFormat = gl.RGBA;
  15866. needConversion = true;
  15867. }
  15868. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15869. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15870. var mipData = mipmapGenerator(faceDataArrays);
  15871. for (var level = 0; level < mipData.length; level++) {
  15872. var mipSize = width >> level;
  15873. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15874. var mipFaceData = mipData[level][faceIndex];
  15875. if (needConversion) {
  15876. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15877. }
  15878. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15879. }
  15880. }
  15881. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15882. }
  15883. else {
  15884. texture.generateMipMaps = !noMipmap;
  15885. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15886. }
  15887. texture.isReady = true;
  15888. // this.resetTextureCache();
  15889. scene._removePendingData(texture);
  15890. if (onLoad) {
  15891. onLoad();
  15892. }
  15893. };
  15894. this._loadFile(url, function (data) {
  15895. internalCallback(data);
  15896. }, undefined, scene.database, true, onerror);
  15897. return texture;
  15898. };
  15899. ;
  15900. /**
  15901. * Update a raw 3D texture
  15902. * @param texture defines the texture to update
  15903. * @param data defines the data to store
  15904. * @param format defines the data format
  15905. * @param invertY defines if data must be stored with Y axis inverted
  15906. * @param compression defines the used compression (can be null)
  15907. */
  15908. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15909. if (compression === void 0) { compression = null; }
  15910. var internalFormat = this._getInternalFormat(format);
  15911. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15912. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15913. if (!this._doNotHandleContextLost) {
  15914. texture._bufferView = data;
  15915. texture.format = format;
  15916. texture.invertY = invertY;
  15917. texture._compression = compression;
  15918. }
  15919. if (texture.width % 4 !== 0) {
  15920. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15921. }
  15922. if (compression && data) {
  15923. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15924. }
  15925. else {
  15926. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15927. }
  15928. if (texture.generateMipMaps) {
  15929. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15930. }
  15931. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15932. // this.resetTextureCache();
  15933. texture.isReady = true;
  15934. };
  15935. /**
  15936. * Creates a new raw 3D texture
  15937. * @param data defines the data used to create the texture
  15938. * @param width defines the width of the texture
  15939. * @param height defines the height of the texture
  15940. * @param depth defines the depth of the texture
  15941. * @param format defines the format of the texture
  15942. * @param generateMipMaps defines if the engine must generate mip levels
  15943. * @param invertY defines if data must be stored with Y axis inverted
  15944. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15945. * @param compression defines the compressed used (can be null)
  15946. * @returns a new raw 3D texture (stored in an InternalTexture)
  15947. */
  15948. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15949. if (compression === void 0) { compression = null; }
  15950. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15951. texture.baseWidth = width;
  15952. texture.baseHeight = height;
  15953. texture.baseDepth = depth;
  15954. texture.width = width;
  15955. texture.height = height;
  15956. texture.depth = depth;
  15957. texture.format = format;
  15958. texture.generateMipMaps = generateMipMaps;
  15959. texture.samplingMode = samplingMode;
  15960. texture.is3D = true;
  15961. if (!this._doNotHandleContextLost) {
  15962. texture._bufferView = data;
  15963. }
  15964. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15965. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15966. // Filters
  15967. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15968. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15969. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15970. if (generateMipMaps) {
  15971. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15972. }
  15973. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15974. this._internalTexturesCache.push(texture);
  15975. return texture;
  15976. };
  15977. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15978. var gl = this._gl;
  15979. if (!gl) {
  15980. return;
  15981. }
  15982. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15983. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15984. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15985. if (!noMipmap && !isCompressed) {
  15986. gl.generateMipmap(gl.TEXTURE_2D);
  15987. }
  15988. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15989. // this.resetTextureCache();
  15990. if (scene) {
  15991. scene._removePendingData(texture);
  15992. }
  15993. texture.onLoadedObservable.notifyObservers(texture);
  15994. texture.onLoadedObservable.clear();
  15995. };
  15996. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15997. var _this = this;
  15998. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15999. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16000. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16001. var gl = this._gl;
  16002. if (!gl) {
  16003. return;
  16004. }
  16005. if (!texture._webGLTexture) {
  16006. // this.resetTextureCache();
  16007. if (scene) {
  16008. scene._removePendingData(texture);
  16009. }
  16010. return;
  16011. }
  16012. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16013. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16014. texture.baseWidth = width;
  16015. texture.baseHeight = height;
  16016. texture.width = potWidth;
  16017. texture.height = potHeight;
  16018. texture.isReady = true;
  16019. if (processFunction(potWidth, potHeight, function () {
  16020. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16021. })) {
  16022. // Returning as texture needs extra async steps
  16023. return;
  16024. }
  16025. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16026. };
  16027. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16028. // Create new RGBA data container.
  16029. var rgbaData;
  16030. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16031. rgbaData = new Float32Array(width * height * 4);
  16032. }
  16033. else {
  16034. rgbaData = new Uint32Array(width * height * 4);
  16035. }
  16036. // Convert each pixel.
  16037. for (var x = 0; x < width; x++) {
  16038. for (var y = 0; y < height; y++) {
  16039. var index = (y * width + x) * 3;
  16040. var newIndex = (y * width + x) * 4;
  16041. // Map Old Value to new value.
  16042. rgbaData[newIndex + 0] = rgbData[index + 0];
  16043. rgbaData[newIndex + 1] = rgbData[index + 1];
  16044. rgbaData[newIndex + 2] = rgbData[index + 2];
  16045. // Add fully opaque alpha channel.
  16046. rgbaData[newIndex + 3] = 1;
  16047. }
  16048. }
  16049. return rgbaData;
  16050. };
  16051. /** @hidden */
  16052. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16053. var gl = this._gl;
  16054. if (texture._framebuffer) {
  16055. gl.deleteFramebuffer(texture._framebuffer);
  16056. texture._framebuffer = null;
  16057. }
  16058. if (texture._depthStencilBuffer) {
  16059. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16060. texture._depthStencilBuffer = null;
  16061. }
  16062. if (texture._MSAAFramebuffer) {
  16063. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16064. texture._MSAAFramebuffer = null;
  16065. }
  16066. if (texture._MSAARenderBuffer) {
  16067. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16068. texture._MSAARenderBuffer = null;
  16069. }
  16070. };
  16071. /** @hidden */
  16072. Engine.prototype._releaseTexture = function (texture) {
  16073. var gl = this._gl;
  16074. this._releaseFramebufferObjects(texture);
  16075. gl.deleteTexture(texture._webGLTexture);
  16076. // Unbind channels
  16077. this.unbindAllTextures();
  16078. var index = this._internalTexturesCache.indexOf(texture);
  16079. if (index !== -1) {
  16080. this._internalTexturesCache.splice(index, 1);
  16081. }
  16082. // Integrated fixed lod samplers.
  16083. if (texture._lodTextureHigh) {
  16084. texture._lodTextureHigh.dispose();
  16085. }
  16086. if (texture._lodTextureMid) {
  16087. texture._lodTextureMid.dispose();
  16088. }
  16089. if (texture._lodTextureLow) {
  16090. texture._lodTextureLow.dispose();
  16091. }
  16092. // Set output texture of post process to null if the texture has been released/disposed
  16093. this.scenes.forEach(function (scene) {
  16094. scene.postProcesses.forEach(function (postProcess) {
  16095. if (postProcess._outputTexture == texture) {
  16096. postProcess._outputTexture = null;
  16097. }
  16098. });
  16099. scene.cameras.forEach(function (camera) {
  16100. camera._postProcesses.forEach(function (postProcess) {
  16101. if (postProcess) {
  16102. if (postProcess._outputTexture == texture) {
  16103. postProcess._outputTexture = null;
  16104. }
  16105. }
  16106. });
  16107. });
  16108. });
  16109. };
  16110. Engine.prototype.setProgram = function (program) {
  16111. if (this._currentProgram !== program) {
  16112. this._gl.useProgram(program);
  16113. this._currentProgram = program;
  16114. }
  16115. };
  16116. /**
  16117. * Binds an effect to the webGL context
  16118. * @param effect defines the effect to bind
  16119. */
  16120. Engine.prototype.bindSamplers = function (effect) {
  16121. this.setProgram(effect.getProgram());
  16122. var samplers = effect.getSamplers();
  16123. for (var index = 0; index < samplers.length; index++) {
  16124. var uniform = effect.getUniform(samplers[index]);
  16125. if (uniform) {
  16126. this._boundUniforms[index] = uniform;
  16127. }
  16128. }
  16129. this._currentEffect = null;
  16130. };
  16131. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16132. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16133. return;
  16134. }
  16135. // Remove
  16136. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16137. // Bind last to it
  16138. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16139. // Bind to dummy
  16140. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16141. };
  16142. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16143. if (!internalTexture) {
  16144. return -1;
  16145. }
  16146. internalTexture._initialSlot = channel;
  16147. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16148. if (channel !== internalTexture._designatedSlot) {
  16149. this._textureCollisions.addCount(1, false);
  16150. }
  16151. }
  16152. else {
  16153. if (channel !== internalTexture._designatedSlot) {
  16154. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16155. return internalTexture._designatedSlot;
  16156. }
  16157. else {
  16158. // No slot for this texture, let's pick a new one (if we find a free slot)
  16159. if (this._nextFreeTextureSlots.length) {
  16160. return this._nextFreeTextureSlots[0];
  16161. }
  16162. // We need to recycle the oldest bound texture, sorry.
  16163. this._textureCollisions.addCount(1, false);
  16164. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16165. }
  16166. }
  16167. }
  16168. return channel;
  16169. };
  16170. Engine.prototype._linkTrackers = function (previous, next) {
  16171. previous.next = next;
  16172. next.previous = previous;
  16173. };
  16174. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16175. var currentSlot = internalTexture._designatedSlot;
  16176. if (currentSlot === -1) {
  16177. return -1;
  16178. }
  16179. internalTexture._designatedSlot = -1;
  16180. if (this.disableTextureBindingOptimization) {
  16181. return -1;
  16182. }
  16183. // Remove from bound list
  16184. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16185. // Free the slot
  16186. this._boundTexturesCache[currentSlot] = null;
  16187. this._nextFreeTextureSlots.push(currentSlot);
  16188. return currentSlot;
  16189. };
  16190. Engine.prototype._activateCurrentTexture = function () {
  16191. if (this._currentTextureChannel !== this._activeChannel) {
  16192. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16193. this._currentTextureChannel = this._activeChannel;
  16194. }
  16195. };
  16196. /** @hidden */
  16197. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16198. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16199. if (force === void 0) { force = false; }
  16200. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16201. this._activeChannel = texture._designatedSlot;
  16202. }
  16203. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16204. var isTextureForRendering = texture && texture._initialSlot > -1;
  16205. if (currentTextureBound !== texture || force) {
  16206. if (currentTextureBound) {
  16207. this._removeDesignatedSlot(currentTextureBound);
  16208. }
  16209. this._activateCurrentTexture();
  16210. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16211. this._boundTexturesCache[this._activeChannel] = texture;
  16212. if (texture) {
  16213. if (!this.disableTextureBindingOptimization) {
  16214. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16215. if (slotIndex > -1) {
  16216. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16217. }
  16218. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16219. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16220. }
  16221. texture._designatedSlot = this._activeChannel;
  16222. }
  16223. }
  16224. else if (forTextureDataUpdate) {
  16225. this._activateCurrentTexture();
  16226. }
  16227. if (isTextureForRendering && !forTextureDataUpdate) {
  16228. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16229. }
  16230. };
  16231. /** @hidden */
  16232. Engine.prototype._bindTexture = function (channel, texture) {
  16233. if (channel < 0) {
  16234. return;
  16235. }
  16236. if (texture) {
  16237. channel = this._getCorrectTextureChannel(channel, texture);
  16238. }
  16239. this._activeChannel = channel;
  16240. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16241. };
  16242. /**
  16243. * Sets a texture to the webGL context from a postprocess
  16244. * @param channel defines the channel to use
  16245. * @param postProcess defines the source postprocess
  16246. */
  16247. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16248. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16249. };
  16250. /**
  16251. * Binds the output of the passed in post process to the texture channel specified
  16252. * @param channel The channel the texture should be bound to
  16253. * @param postProcess The post process which's output should be bound
  16254. */
  16255. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16256. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16257. };
  16258. /**
  16259. * Unbind all textures from the webGL context
  16260. */
  16261. Engine.prototype.unbindAllTextures = function () {
  16262. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16263. this._activeChannel = channel;
  16264. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16265. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16266. if (this.webGLVersion > 1) {
  16267. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16268. }
  16269. }
  16270. };
  16271. /**
  16272. * Sets a texture to the according uniform.
  16273. * @param channel The texture channel
  16274. * @param uniform The uniform to set
  16275. * @param texture The texture to apply
  16276. */
  16277. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16278. if (channel < 0) {
  16279. return;
  16280. }
  16281. if (uniform) {
  16282. this._boundUniforms[channel] = uniform;
  16283. }
  16284. this._setTexture(channel, texture);
  16285. };
  16286. /**
  16287. * Sets a depth stencil texture from a render target to the according uniform.
  16288. * @param channel The texture channel
  16289. * @param uniform The uniform to set
  16290. * @param texture The render target texture containing the depth stencil texture to apply
  16291. */
  16292. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16293. if (channel < 0) {
  16294. return;
  16295. }
  16296. if (uniform) {
  16297. this._boundUniforms[channel] = uniform;
  16298. }
  16299. if (!texture || !texture.depthStencilTexture) {
  16300. this._setTexture(channel, null);
  16301. }
  16302. else {
  16303. this._setTexture(channel, texture, false, true);
  16304. }
  16305. };
  16306. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16307. var uniform = this._boundUniforms[sourceSlot];
  16308. if (uniform._currentState === destination) {
  16309. return;
  16310. }
  16311. this._gl.uniform1i(uniform, destination);
  16312. uniform._currentState = destination;
  16313. };
  16314. Engine.prototype._getTextureWrapMode = function (mode) {
  16315. switch (mode) {
  16316. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16317. return this._gl.REPEAT;
  16318. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16319. return this._gl.CLAMP_TO_EDGE;
  16320. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16321. return this._gl.MIRRORED_REPEAT;
  16322. }
  16323. return this._gl.REPEAT;
  16324. };
  16325. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16326. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16327. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16328. // Not ready?
  16329. if (!texture) {
  16330. if (this._boundTexturesCache[channel] != null) {
  16331. this._activeChannel = channel;
  16332. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16333. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16334. if (this.webGLVersion > 1) {
  16335. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16336. }
  16337. }
  16338. return false;
  16339. }
  16340. // Video
  16341. if (texture.video) {
  16342. this._activeChannel = channel;
  16343. texture.update();
  16344. }
  16345. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16346. texture.delayLoad();
  16347. return false;
  16348. }
  16349. var internalTexture;
  16350. if (depthStencilTexture) {
  16351. internalTexture = texture.depthStencilTexture;
  16352. }
  16353. else if (texture.isReady()) {
  16354. internalTexture = texture.getInternalTexture();
  16355. }
  16356. else if (texture.isCube) {
  16357. internalTexture = this.emptyCubeTexture;
  16358. }
  16359. else if (texture.is3D) {
  16360. internalTexture = this.emptyTexture3D;
  16361. }
  16362. else {
  16363. internalTexture = this.emptyTexture;
  16364. }
  16365. if (!isPartOfTextureArray) {
  16366. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16367. }
  16368. var needToBind = true;
  16369. if (this._boundTexturesCache[channel] === internalTexture) {
  16370. this._moveBoundTextureOnTop(internalTexture);
  16371. if (!isPartOfTextureArray) {
  16372. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16373. }
  16374. needToBind = false;
  16375. }
  16376. this._activeChannel = channel;
  16377. if (internalTexture && internalTexture.is3D) {
  16378. if (needToBind) {
  16379. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16380. }
  16381. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16382. internalTexture._cachedWrapU = texture.wrapU;
  16383. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16384. }
  16385. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16386. internalTexture._cachedWrapV = texture.wrapV;
  16387. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16388. }
  16389. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16390. internalTexture._cachedWrapR = texture.wrapR;
  16391. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16392. }
  16393. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16394. }
  16395. else if (internalTexture && internalTexture.isCube) {
  16396. if (needToBind) {
  16397. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16398. }
  16399. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16400. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16401. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16402. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16403. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16404. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16405. }
  16406. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16407. }
  16408. else {
  16409. if (needToBind) {
  16410. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16411. }
  16412. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16413. internalTexture._cachedWrapU = texture.wrapU;
  16414. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16415. }
  16416. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16417. internalTexture._cachedWrapV = texture.wrapV;
  16418. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16419. }
  16420. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16421. }
  16422. return true;
  16423. };
  16424. /**
  16425. * Sets an array of texture to the webGL context
  16426. * @param channel defines the channel where the texture array must be set
  16427. * @param uniform defines the associated uniform location
  16428. * @param textures defines the array of textures to bind
  16429. */
  16430. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16431. if (channel < 0 || !uniform) {
  16432. return;
  16433. }
  16434. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16435. this._textureUnits = new Int32Array(textures.length);
  16436. }
  16437. for (var i = 0; i < textures.length; i++) {
  16438. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16439. }
  16440. this._gl.uniform1iv(uniform, this._textureUnits);
  16441. for (var index = 0; index < textures.length; index++) {
  16442. this._setTexture(this._textureUnits[index], textures[index], true);
  16443. }
  16444. };
  16445. /** @hidden */
  16446. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16447. var internalTexture = texture.getInternalTexture();
  16448. if (!internalTexture) {
  16449. return;
  16450. }
  16451. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16452. var value = texture.anisotropicFilteringLevel;
  16453. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16454. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16455. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16456. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16457. }
  16458. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16459. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16460. internalTexture._cachedAnisotropicFilteringLevel = value;
  16461. }
  16462. };
  16463. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16464. this._bindTextureDirectly(target, texture, true, true);
  16465. this._gl.texParameterf(target, parameter, value);
  16466. };
  16467. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16468. if (texture) {
  16469. this._bindTextureDirectly(target, texture, true, true);
  16470. }
  16471. this._gl.texParameteri(target, parameter, value);
  16472. };
  16473. /**
  16474. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16475. * @param x defines the x coordinate of the rectangle where pixels must be read
  16476. * @param y defines the y coordinate of the rectangle where pixels must be read
  16477. * @param width defines the width of the rectangle where pixels must be read
  16478. * @param height defines the height of the rectangle where pixels must be read
  16479. * @returns a Uint8Array containing RGBA colors
  16480. */
  16481. Engine.prototype.readPixels = function (x, y, width, height) {
  16482. var data = new Uint8Array(height * width * 4);
  16483. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16484. return data;
  16485. };
  16486. /**
  16487. * Add an externaly attached data from its key.
  16488. * This method call will fail and return false, if such key already exists.
  16489. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16490. * @param key the unique key that identifies the data
  16491. * @param data the data object to associate to the key for this Engine instance
  16492. * @return true if no such key were already present and the data was added successfully, false otherwise
  16493. */
  16494. Engine.prototype.addExternalData = function (key, data) {
  16495. if (!this._externalData) {
  16496. this._externalData = new BABYLON.StringDictionary();
  16497. }
  16498. return this._externalData.add(key, data);
  16499. };
  16500. /**
  16501. * Get an externaly attached data from its key
  16502. * @param key the unique key that identifies the data
  16503. * @return the associated data, if present (can be null), or undefined if not present
  16504. */
  16505. Engine.prototype.getExternalData = function (key) {
  16506. if (!this._externalData) {
  16507. this._externalData = new BABYLON.StringDictionary();
  16508. }
  16509. return this._externalData.get(key);
  16510. };
  16511. /**
  16512. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16513. * @param key the unique key that identifies the data
  16514. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16515. * @return the associated data, can be null if the factory returned null.
  16516. */
  16517. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16518. if (!this._externalData) {
  16519. this._externalData = new BABYLON.StringDictionary();
  16520. }
  16521. return this._externalData.getOrAddWithFactory(key, factory);
  16522. };
  16523. /**
  16524. * Remove an externaly attached data from the Engine instance
  16525. * @param key the unique key that identifies the data
  16526. * @return true if the data was successfully removed, false if it doesn't exist
  16527. */
  16528. Engine.prototype.removeExternalData = function (key) {
  16529. if (!this._externalData) {
  16530. this._externalData = new BABYLON.StringDictionary();
  16531. }
  16532. return this._externalData.remove(key);
  16533. };
  16534. /**
  16535. * Unbind all vertex attributes from the webGL context
  16536. */
  16537. Engine.prototype.unbindAllAttributes = function () {
  16538. if (this._mustWipeVertexAttributes) {
  16539. this._mustWipeVertexAttributes = false;
  16540. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16541. this._gl.disableVertexAttribArray(i);
  16542. this._vertexAttribArraysEnabled[i] = false;
  16543. this._currentBufferPointers[i].active = false;
  16544. }
  16545. return;
  16546. }
  16547. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16548. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16549. continue;
  16550. }
  16551. this._gl.disableVertexAttribArray(i);
  16552. this._vertexAttribArraysEnabled[i] = false;
  16553. this._currentBufferPointers[i].active = false;
  16554. }
  16555. };
  16556. /**
  16557. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16558. */
  16559. Engine.prototype.releaseEffects = function () {
  16560. for (var name in this._compiledEffects) {
  16561. this._deleteProgram(this._compiledEffects[name]._program);
  16562. }
  16563. this._compiledEffects = {};
  16564. };
  16565. /**
  16566. * Dispose and release all associated resources
  16567. */
  16568. Engine.prototype.dispose = function () {
  16569. this.hideLoadingUI();
  16570. this.stopRenderLoop();
  16571. // Release postProcesses
  16572. while (this.postProcesses.length) {
  16573. this.postProcesses[0].dispose();
  16574. }
  16575. // Empty texture
  16576. if (this._emptyTexture) {
  16577. this._releaseTexture(this._emptyTexture);
  16578. this._emptyTexture = null;
  16579. }
  16580. if (this._emptyCubeTexture) {
  16581. this._releaseTexture(this._emptyCubeTexture);
  16582. this._emptyCubeTexture = null;
  16583. }
  16584. // Rescale PP
  16585. if (this._rescalePostProcess) {
  16586. this._rescalePostProcess.dispose();
  16587. }
  16588. // Release scenes
  16589. while (this.scenes.length) {
  16590. this.scenes[0].dispose();
  16591. }
  16592. // Release audio engine
  16593. if (Engine.audioEngine) {
  16594. Engine.audioEngine.dispose();
  16595. }
  16596. // Release effects
  16597. this.releaseEffects();
  16598. // Unbind
  16599. this.unbindAllAttributes();
  16600. this._boundUniforms = [];
  16601. if (this._dummyFramebuffer) {
  16602. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16603. }
  16604. //WebVR
  16605. this.disableVR();
  16606. // Events
  16607. if (BABYLON.Tools.IsWindowObjectExist()) {
  16608. window.removeEventListener("blur", this._onBlur);
  16609. window.removeEventListener("focus", this._onFocus);
  16610. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16611. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16612. if (this._renderingCanvas) {
  16613. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16614. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16615. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16616. if (!this._doNotHandleContextLost) {
  16617. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16618. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16619. }
  16620. }
  16621. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16622. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16623. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16624. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16625. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16626. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16627. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16628. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16629. if (this._onVrDisplayConnect) {
  16630. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16631. if (this._onVrDisplayDisconnect) {
  16632. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16633. }
  16634. if (this._onVrDisplayPresentChange) {
  16635. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16636. }
  16637. this._onVrDisplayConnect = null;
  16638. this._onVrDisplayDisconnect = null;
  16639. }
  16640. }
  16641. // Remove from Instances
  16642. var index = Engine.Instances.indexOf(this);
  16643. if (index >= 0) {
  16644. Engine.Instances.splice(index, 1);
  16645. }
  16646. this._workingCanvas = null;
  16647. this._workingContext = null;
  16648. this._currentBufferPointers = [];
  16649. this._renderingCanvas = null;
  16650. this._currentProgram = null;
  16651. this._bindedRenderFunction = null;
  16652. this.onResizeObservable.clear();
  16653. this.onCanvasBlurObservable.clear();
  16654. this.onCanvasFocusObservable.clear();
  16655. this.onCanvasPointerOutObservable.clear();
  16656. this.onBeginFrameObservable.clear();
  16657. this.onEndFrameObservable.clear();
  16658. BABYLON.Effect.ResetCache();
  16659. // Abort active requests
  16660. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16661. var request = _a[_i];
  16662. request.abort();
  16663. }
  16664. };
  16665. // Loading screen
  16666. /**
  16667. * Display the loading screen
  16668. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16669. */
  16670. Engine.prototype.displayLoadingUI = function () {
  16671. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16672. return;
  16673. }
  16674. var loadingScreen = this.loadingScreen;
  16675. if (loadingScreen) {
  16676. loadingScreen.displayLoadingUI();
  16677. }
  16678. };
  16679. /**
  16680. * Hide the loading screen
  16681. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16682. */
  16683. Engine.prototype.hideLoadingUI = function () {
  16684. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16685. return;
  16686. }
  16687. var loadingScreen = this.loadingScreen;
  16688. if (loadingScreen) {
  16689. loadingScreen.hideLoadingUI();
  16690. }
  16691. };
  16692. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16693. /**
  16694. * Gets the current loading screen object
  16695. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16696. */
  16697. get: function () {
  16698. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16699. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16700. return this._loadingScreen;
  16701. },
  16702. /**
  16703. * Sets the current loading screen object
  16704. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16705. */
  16706. set: function (loadingScreen) {
  16707. this._loadingScreen = loadingScreen;
  16708. },
  16709. enumerable: true,
  16710. configurable: true
  16711. });
  16712. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16713. /**
  16714. * Sets the current loading screen text
  16715. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16716. */
  16717. set: function (text) {
  16718. this.loadingScreen.loadingUIText = text;
  16719. },
  16720. enumerable: true,
  16721. configurable: true
  16722. });
  16723. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16724. /**
  16725. * Sets the current loading screen background color
  16726. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16727. */
  16728. set: function (color) {
  16729. this.loadingScreen.loadingUIBackgroundColor = color;
  16730. },
  16731. enumerable: true,
  16732. configurable: true
  16733. });
  16734. /**
  16735. * Attach a new callback raised when context lost event is fired
  16736. * @param callback defines the callback to call
  16737. */
  16738. Engine.prototype.attachContextLostEvent = function (callback) {
  16739. if (this._renderingCanvas) {
  16740. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16741. }
  16742. };
  16743. /**
  16744. * Attach a new callback raised when context restored event is fired
  16745. * @param callback defines the callback to call
  16746. */
  16747. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16748. if (this._renderingCanvas) {
  16749. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16750. }
  16751. };
  16752. /**
  16753. * Gets the source code of the vertex shader associated with a specific webGL program
  16754. * @param program defines the program to use
  16755. * @returns a string containing the source code of the vertex shader associated with the program
  16756. */
  16757. Engine.prototype.getVertexShaderSource = function (program) {
  16758. var shaders = this._gl.getAttachedShaders(program);
  16759. if (!shaders) {
  16760. return null;
  16761. }
  16762. return this._gl.getShaderSource(shaders[0]);
  16763. };
  16764. /**
  16765. * Gets the source code of the fragment shader associated with a specific webGL program
  16766. * @param program defines the program to use
  16767. * @returns a string containing the source code of the fragment shader associated with the program
  16768. */
  16769. Engine.prototype.getFragmentShaderSource = function (program) {
  16770. var shaders = this._gl.getAttachedShaders(program);
  16771. if (!shaders) {
  16772. return null;
  16773. }
  16774. return this._gl.getShaderSource(shaders[1]);
  16775. };
  16776. /**
  16777. * Get the current error code of the webGL context
  16778. * @returns the error code
  16779. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16780. */
  16781. Engine.prototype.getError = function () {
  16782. return this._gl.getError();
  16783. };
  16784. // FPS
  16785. /**
  16786. * Gets the current framerate
  16787. * @returns a number representing the framerate
  16788. */
  16789. Engine.prototype.getFps = function () {
  16790. return this._fps;
  16791. };
  16792. /**
  16793. * Gets the time spent between current and previous frame
  16794. * @returns a number representing the delta time in ms
  16795. */
  16796. Engine.prototype.getDeltaTime = function () {
  16797. return this._deltaTime;
  16798. };
  16799. Engine.prototype._measureFps = function () {
  16800. this._performanceMonitor.sampleFrame();
  16801. this._fps = this._performanceMonitor.averageFPS;
  16802. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16803. };
  16804. /** @hidden */
  16805. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16806. if (faceIndex === void 0) { faceIndex = -1; }
  16807. var gl = this._gl;
  16808. if (!this._dummyFramebuffer) {
  16809. var dummy = gl.createFramebuffer();
  16810. if (!dummy) {
  16811. throw new Error("Unable to create dummy framebuffer");
  16812. }
  16813. this._dummyFramebuffer = dummy;
  16814. }
  16815. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16816. if (faceIndex > -1) {
  16817. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16818. }
  16819. else {
  16820. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16821. }
  16822. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16823. var buffer;
  16824. switch (readType) {
  16825. case gl.UNSIGNED_BYTE:
  16826. buffer = new Uint8Array(4 * width * height);
  16827. readType = gl.UNSIGNED_BYTE;
  16828. break;
  16829. default:
  16830. buffer = new Float32Array(4 * width * height);
  16831. readType = gl.FLOAT;
  16832. break;
  16833. }
  16834. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16835. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16836. return buffer;
  16837. };
  16838. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16839. if (this._webGLVersion > 1) {
  16840. return this._caps.colorBufferFloat;
  16841. }
  16842. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16843. };
  16844. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16845. if (this._webGLVersion > 1) {
  16846. return this._caps.colorBufferFloat;
  16847. }
  16848. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16849. };
  16850. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16851. Engine.prototype._canRenderToFramebuffer = function (type) {
  16852. var gl = this._gl;
  16853. //clear existing errors
  16854. while (gl.getError() !== gl.NO_ERROR) { }
  16855. var successful = true;
  16856. var texture = gl.createTexture();
  16857. gl.bindTexture(gl.TEXTURE_2D, texture);
  16858. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16859. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16860. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16861. var fb = gl.createFramebuffer();
  16862. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16863. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16864. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16865. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16866. successful = successful && (gl.getError() === gl.NO_ERROR);
  16867. //try render by clearing frame buffer's color buffer
  16868. if (successful) {
  16869. gl.clear(gl.COLOR_BUFFER_BIT);
  16870. successful = successful && (gl.getError() === gl.NO_ERROR);
  16871. }
  16872. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16873. if (successful) {
  16874. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16875. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16876. var readFormat = gl.RGBA;
  16877. var readType = gl.UNSIGNED_BYTE;
  16878. var buffer = new Uint8Array(4);
  16879. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16880. successful = successful && (gl.getError() === gl.NO_ERROR);
  16881. }
  16882. //clean up
  16883. gl.deleteTexture(texture);
  16884. gl.deleteFramebuffer(fb);
  16885. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16886. //clear accumulated errors
  16887. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16888. return successful;
  16889. };
  16890. /** @hidden */
  16891. Engine.prototype._getWebGLTextureType = function (type) {
  16892. if (type === Engine.TEXTURETYPE_FLOAT) {
  16893. return this._gl.FLOAT;
  16894. }
  16895. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16896. // Add Half Float Constant.
  16897. return this._gl.HALF_FLOAT_OES;
  16898. }
  16899. return this._gl.UNSIGNED_BYTE;
  16900. };
  16901. ;
  16902. Engine.prototype._getInternalFormat = function (format) {
  16903. var internalFormat = this._gl.RGBA;
  16904. switch (format) {
  16905. case Engine.TEXTUREFORMAT_ALPHA:
  16906. internalFormat = this._gl.ALPHA;
  16907. break;
  16908. case Engine.TEXTUREFORMAT_LUMINANCE:
  16909. internalFormat = this._gl.LUMINANCE;
  16910. break;
  16911. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16912. internalFormat = this._gl.LUMINANCE_ALPHA;
  16913. break;
  16914. case Engine.TEXTUREFORMAT_RGB:
  16915. case Engine.TEXTUREFORMAT_RGB32F:
  16916. internalFormat = this._gl.RGB;
  16917. break;
  16918. case Engine.TEXTUREFORMAT_RGBA:
  16919. case Engine.TEXTUREFORMAT_RGBA32F:
  16920. internalFormat = this._gl.RGBA;
  16921. break;
  16922. case Engine.TEXTUREFORMAT_R32F:
  16923. internalFormat = this._gl.RED;
  16924. break;
  16925. case Engine.TEXTUREFORMAT_RG32F:
  16926. internalFormat = this._gl.RG;
  16927. break;
  16928. }
  16929. return internalFormat;
  16930. };
  16931. /** @hidden */
  16932. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16933. if (this._webGLVersion === 1) {
  16934. if (format) {
  16935. switch (format) {
  16936. case Engine.TEXTUREFORMAT_LUMINANCE:
  16937. return this._gl.LUMINANCE;
  16938. }
  16939. }
  16940. return this._gl.RGBA;
  16941. }
  16942. if (type === Engine.TEXTURETYPE_FLOAT) {
  16943. if (format) {
  16944. switch (format) {
  16945. case Engine.TEXTUREFORMAT_R32F:
  16946. return this._gl.R32F;
  16947. case Engine.TEXTUREFORMAT_RG32F:
  16948. return this._gl.RG32F;
  16949. case Engine.TEXTUREFORMAT_RGB32F:
  16950. return this._gl.RGB32F;
  16951. }
  16952. }
  16953. return this._gl.RGBA32F;
  16954. }
  16955. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16956. return this._gl.RGBA16F;
  16957. }
  16958. if (format) {
  16959. switch (format) {
  16960. case Engine.TEXTUREFORMAT_LUMINANCE:
  16961. return this._gl.LUMINANCE;
  16962. case Engine.TEXTUREFORMAT_RGB:
  16963. return this._gl.RGB;
  16964. }
  16965. }
  16966. return this._gl.RGBA;
  16967. };
  16968. ;
  16969. /** @hidden */
  16970. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16971. if (type === Engine.TEXTURETYPE_FLOAT) {
  16972. return this._gl.RGBA32F;
  16973. }
  16974. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16975. return this._gl.RGBA16F;
  16976. }
  16977. return this._gl.RGBA8;
  16978. };
  16979. ;
  16980. /**
  16981. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16982. * @return the new query
  16983. */
  16984. Engine.prototype.createQuery = function () {
  16985. return this._gl.createQuery();
  16986. };
  16987. /**
  16988. * Delete and release a webGL query
  16989. * @param query defines the query to delete
  16990. * @return the current engine
  16991. */
  16992. Engine.prototype.deleteQuery = function (query) {
  16993. this._gl.deleteQuery(query);
  16994. return this;
  16995. };
  16996. /**
  16997. * Check if a given query has resolved and got its value
  16998. * @param query defines the query to check
  16999. * @returns true if the query got its value
  17000. */
  17001. Engine.prototype.isQueryResultAvailable = function (query) {
  17002. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17003. };
  17004. /**
  17005. * Gets the value of a given query
  17006. * @param query defines the query to check
  17007. * @returns the value of the query
  17008. */
  17009. Engine.prototype.getQueryResult = function (query) {
  17010. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17011. };
  17012. /**
  17013. * Initiates an occlusion query
  17014. * @param algorithmType defines the algorithm to use
  17015. * @param query defines the query to use
  17016. * @returns the current engine
  17017. * @see http://doc.babylonjs.com/features/occlusionquery
  17018. */
  17019. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17020. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17021. this._gl.beginQuery(glAlgorithm, query);
  17022. return this;
  17023. };
  17024. /**
  17025. * Ends an occlusion query
  17026. * @see http://doc.babylonjs.com/features/occlusionquery
  17027. * @param algorithmType defines the algorithm to use
  17028. * @returns the current engine
  17029. */
  17030. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17031. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17032. this._gl.endQuery(glAlgorithm);
  17033. return this;
  17034. };
  17035. /* Time queries */
  17036. Engine.prototype._createTimeQuery = function () {
  17037. var timerQuery = this._caps.timerQuery;
  17038. if (timerQuery.createQueryEXT) {
  17039. return timerQuery.createQueryEXT();
  17040. }
  17041. return this.createQuery();
  17042. };
  17043. Engine.prototype._deleteTimeQuery = function (query) {
  17044. var timerQuery = this._caps.timerQuery;
  17045. if (timerQuery.deleteQueryEXT) {
  17046. timerQuery.deleteQueryEXT(query);
  17047. return;
  17048. }
  17049. this.deleteQuery(query);
  17050. };
  17051. Engine.prototype._getTimeQueryResult = function (query) {
  17052. var timerQuery = this._caps.timerQuery;
  17053. if (timerQuery.getQueryObjectEXT) {
  17054. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17055. }
  17056. return this.getQueryResult(query);
  17057. };
  17058. Engine.prototype._getTimeQueryAvailability = function (query) {
  17059. var timerQuery = this._caps.timerQuery;
  17060. if (timerQuery.getQueryObjectEXT) {
  17061. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17062. }
  17063. return this.isQueryResultAvailable(query);
  17064. };
  17065. /**
  17066. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17067. * Please note that only one query can be issued at a time
  17068. * @returns a time token used to track the time span
  17069. */
  17070. Engine.prototype.startTimeQuery = function () {
  17071. var timerQuery = this._caps.timerQuery;
  17072. if (!timerQuery) {
  17073. return null;
  17074. }
  17075. var token = new BABYLON._TimeToken();
  17076. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17077. if (this._caps.canUseTimestampForTimerQuery) {
  17078. token._startTimeQuery = this._createTimeQuery();
  17079. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17080. }
  17081. else {
  17082. if (this._currentNonTimestampToken) {
  17083. return this._currentNonTimestampToken;
  17084. }
  17085. token._timeElapsedQuery = this._createTimeQuery();
  17086. if (timerQuery.beginQueryEXT) {
  17087. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17088. }
  17089. else {
  17090. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17091. }
  17092. this._currentNonTimestampToken = token;
  17093. }
  17094. return token;
  17095. };
  17096. /**
  17097. * Ends a time query
  17098. * @param token defines the token used to measure the time span
  17099. * @returns the time spent (in ns)
  17100. */
  17101. Engine.prototype.endTimeQuery = function (token) {
  17102. var timerQuery = this._caps.timerQuery;
  17103. if (!timerQuery || !token) {
  17104. return -1;
  17105. }
  17106. if (this._caps.canUseTimestampForTimerQuery) {
  17107. if (!token._startTimeQuery) {
  17108. return -1;
  17109. }
  17110. if (!token._endTimeQuery) {
  17111. token._endTimeQuery = this._createTimeQuery();
  17112. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17113. }
  17114. }
  17115. else if (!token._timeElapsedQueryEnded) {
  17116. if (!token._timeElapsedQuery) {
  17117. return -1;
  17118. }
  17119. if (timerQuery.endQueryEXT) {
  17120. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17121. }
  17122. else {
  17123. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17124. }
  17125. token._timeElapsedQueryEnded = true;
  17126. }
  17127. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17128. var available = false;
  17129. if (token._endTimeQuery) {
  17130. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17131. }
  17132. else if (token._timeElapsedQuery) {
  17133. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17134. }
  17135. if (available && !disjoint) {
  17136. var result = 0;
  17137. if (this._caps.canUseTimestampForTimerQuery) {
  17138. if (!token._startTimeQuery || !token._endTimeQuery) {
  17139. return -1;
  17140. }
  17141. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17142. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17143. result = timeEnd - timeStart;
  17144. this._deleteTimeQuery(token._startTimeQuery);
  17145. this._deleteTimeQuery(token._endTimeQuery);
  17146. token._startTimeQuery = null;
  17147. token._endTimeQuery = null;
  17148. }
  17149. else {
  17150. if (!token._timeElapsedQuery) {
  17151. return -1;
  17152. }
  17153. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17154. this._deleteTimeQuery(token._timeElapsedQuery);
  17155. token._timeElapsedQuery = null;
  17156. token._timeElapsedQueryEnded = false;
  17157. this._currentNonTimestampToken = null;
  17158. }
  17159. return result;
  17160. }
  17161. return -1;
  17162. };
  17163. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17164. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17165. };
  17166. // Transform feedback
  17167. /**
  17168. * Creates a webGL transform feedback object
  17169. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17170. * @returns the webGL transform feedback object
  17171. */
  17172. Engine.prototype.createTransformFeedback = function () {
  17173. return this._gl.createTransformFeedback();
  17174. };
  17175. /**
  17176. * Delete a webGL transform feedback object
  17177. * @param value defines the webGL transform feedback object to delete
  17178. */
  17179. Engine.prototype.deleteTransformFeedback = function (value) {
  17180. this._gl.deleteTransformFeedback(value);
  17181. };
  17182. /**
  17183. * Bind a webGL transform feedback object to the webgl context
  17184. * @param value defines the webGL transform feedback object to bind
  17185. */
  17186. Engine.prototype.bindTransformFeedback = function (value) {
  17187. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17188. };
  17189. /**
  17190. * Begins a transform feedback operation
  17191. * @param usePoints defines if points or triangles must be used
  17192. */
  17193. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17194. if (usePoints === void 0) { usePoints = true; }
  17195. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17196. };
  17197. /**
  17198. * Ends a transform feedback operation
  17199. */
  17200. Engine.prototype.endTransformFeedback = function () {
  17201. this._gl.endTransformFeedback();
  17202. };
  17203. /**
  17204. * Specify the varyings to use with transform feedback
  17205. * @param program defines the associated webGL program
  17206. * @param value defines the list of strings representing the varying names
  17207. */
  17208. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17209. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17210. };
  17211. /**
  17212. * Bind a webGL buffer for a transform feedback operation
  17213. * @param value defines the webGL buffer to bind
  17214. */
  17215. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17216. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17217. };
  17218. /** @hidden */
  17219. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17220. var _this = this;
  17221. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17222. this._activeRequests.push(request);
  17223. request.onCompleteObservable.add(function (request) {
  17224. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17225. });
  17226. return request;
  17227. };
  17228. /** @hidden */
  17229. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17230. var _this = this;
  17231. return new Promise(function (resolve, reject) {
  17232. _this._loadFile(url, function (data) {
  17233. resolve(data);
  17234. }, undefined, database, useArrayBuffer, function (request, exception) {
  17235. reject(exception);
  17236. });
  17237. });
  17238. };
  17239. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17240. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17241. var onload = function (data) {
  17242. loadedFiles[index] = data;
  17243. loadedFiles._internalCount++;
  17244. if (loadedFiles._internalCount === 6) {
  17245. onfinish(loadedFiles);
  17246. }
  17247. };
  17248. var onerror = function (request, exception) {
  17249. if (onErrorCallBack && request) {
  17250. onErrorCallBack(request.status + " " + request.statusText, exception);
  17251. }
  17252. };
  17253. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17254. };
  17255. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17256. if (onError === void 0) { onError = null; }
  17257. var loadedFiles = [];
  17258. loadedFiles._internalCount = 0;
  17259. for (var index = 0; index < 6; index++) {
  17260. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17261. }
  17262. };
  17263. // Statics
  17264. /**
  17265. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17266. * @returns true if the engine can be created
  17267. * @ignorenaming
  17268. */
  17269. Engine.isSupported = function () {
  17270. try {
  17271. var tempcanvas = document.createElement("canvas");
  17272. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17273. return gl != null && !!window.WebGLRenderingContext;
  17274. }
  17275. catch (e) {
  17276. return false;
  17277. }
  17278. };
  17279. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17280. Engine.ExceptionList = [
  17281. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17282. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17283. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17284. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17285. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17286. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17287. ];
  17288. /** Gets the list of created engines */
  17289. Engine.Instances = new Array();
  17290. // Const statics
  17291. Engine._ALPHA_DISABLE = 0;
  17292. Engine._ALPHA_ADD = 1;
  17293. Engine._ALPHA_COMBINE = 2;
  17294. Engine._ALPHA_SUBTRACT = 3;
  17295. Engine._ALPHA_MULTIPLY = 4;
  17296. Engine._ALPHA_MAXIMIZED = 5;
  17297. Engine._ALPHA_ONEONE = 6;
  17298. Engine._ALPHA_PREMULTIPLIED = 7;
  17299. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17300. Engine._ALPHA_INTERPOLATE = 9;
  17301. Engine._ALPHA_SCREENMODE = 10;
  17302. Engine._DELAYLOADSTATE_NONE = 0;
  17303. Engine._DELAYLOADSTATE_LOADED = 1;
  17304. Engine._DELAYLOADSTATE_LOADING = 2;
  17305. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17306. Engine._TEXTUREFORMAT_ALPHA = 0;
  17307. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17308. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17309. Engine._TEXTUREFORMAT_RGB = 4;
  17310. Engine._TEXTUREFORMAT_RGBA = 5;
  17311. Engine._TEXTUREFORMAT_R32F = 6;
  17312. Engine._TEXTUREFORMAT_RG32F = 7;
  17313. Engine._TEXTUREFORMAT_RGB32F = 8;
  17314. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17315. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17316. Engine._TEXTURETYPE_FLOAT = 1;
  17317. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17318. // Depht or Stencil test Constants.
  17319. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17320. 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.
  17321. 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.
  17322. 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.
  17323. 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.
  17324. 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.
  17325. 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.
  17326. 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.
  17327. // Stencil Actions Constants.
  17328. Engine._KEEP = 0x1E00;
  17329. Engine._REPLACE = 0x1E01;
  17330. Engine._INCR = 0x1E02;
  17331. Engine._DECR = 0x1E03;
  17332. Engine._INVERT = 0x150A;
  17333. Engine._INCR_WRAP = 0x8507;
  17334. Engine._DECR_WRAP = 0x8508;
  17335. // Texture rescaling mode
  17336. Engine._SCALEMODE_FLOOR = 1;
  17337. Engine._SCALEMODE_NEAREST = 2;
  17338. Engine._SCALEMODE_CEILING = 3;
  17339. // Updatable statics so stick with vars here
  17340. /**
  17341. * Gets or sets the epsilon value used by collision engine
  17342. */
  17343. Engine.CollisionsEpsilon = 0.001;
  17344. /**
  17345. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17346. */
  17347. Engine.CodeRepository = "src/";
  17348. /**
  17349. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17350. */
  17351. Engine.ShadersRepository = "src/Shaders/";
  17352. return Engine;
  17353. }());
  17354. BABYLON.Engine = Engine;
  17355. })(BABYLON || (BABYLON = {}));
  17356. //# sourceMappingURL=babylon.engine.js.map
  17357. var BABYLON;
  17358. (function (BABYLON) {
  17359. /**
  17360. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17361. */
  17362. var Node = /** @class */ (function () {
  17363. /**
  17364. * Creates a new Node
  17365. * @param {string} name - the name and id to be given to this node
  17366. * @param {BABYLON.Scene} the scene this node will be added to
  17367. */
  17368. function Node(name, scene) {
  17369. if (scene === void 0) { scene = null; }
  17370. /**
  17371. * Gets or sets a string used to store user defined state for the node
  17372. */
  17373. this.state = "";
  17374. /**
  17375. * Gets or sets an object used to store user defined information for the node
  17376. */
  17377. this.metadata = null;
  17378. /**
  17379. * Gets or sets a boolean used to define if the node must be serialized
  17380. */
  17381. this.doNotSerialize = false;
  17382. /** @hidden */
  17383. this._isDisposed = false;
  17384. /**
  17385. * Gets a list of Animations associated with the node
  17386. */
  17387. this.animations = new Array();
  17388. this._ranges = {};
  17389. this._isEnabled = true;
  17390. this._isReady = true;
  17391. /** @hidden */
  17392. this._currentRenderId = -1;
  17393. this._parentRenderId = -1;
  17394. this._childRenderId = -1;
  17395. this._animationPropertiesOverride = null;
  17396. /**
  17397. * An event triggered when the mesh is disposed
  17398. */
  17399. this.onDisposeObservable = new BABYLON.Observable();
  17400. // Behaviors
  17401. this._behaviors = new Array();
  17402. this.name = name;
  17403. this.id = name;
  17404. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17405. this.uniqueId = this._scene.getUniqueId();
  17406. this._initCache();
  17407. }
  17408. /**
  17409. * Gets a boolean indicating if the node has been disposed
  17410. * @returns true if the node was disposed
  17411. */
  17412. Node.prototype.isDisposed = function () {
  17413. return this._isDisposed;
  17414. };
  17415. Object.defineProperty(Node.prototype, "parent", {
  17416. get: function () {
  17417. return this._parentNode;
  17418. },
  17419. /**
  17420. * Gets or sets the parent of the node
  17421. */
  17422. set: function (parent) {
  17423. if (this._parentNode === parent) {
  17424. return;
  17425. }
  17426. // Remove self from list of children of parent
  17427. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17428. var index = this._parentNode._children.indexOf(this);
  17429. if (index !== -1) {
  17430. this._parentNode._children.splice(index, 1);
  17431. }
  17432. }
  17433. // Store new parent
  17434. this._parentNode = parent;
  17435. // Add as child to new parent
  17436. if (this._parentNode) {
  17437. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17438. this._parentNode._children = new Array();
  17439. }
  17440. this._parentNode._children.push(this);
  17441. }
  17442. },
  17443. enumerable: true,
  17444. configurable: true
  17445. });
  17446. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17447. /**
  17448. * Gets or sets the animation properties override
  17449. */
  17450. get: function () {
  17451. if (!this._animationPropertiesOverride) {
  17452. return this._scene.animationPropertiesOverride;
  17453. }
  17454. return this._animationPropertiesOverride;
  17455. },
  17456. set: function (value) {
  17457. this._animationPropertiesOverride = value;
  17458. },
  17459. enumerable: true,
  17460. configurable: true
  17461. });
  17462. /**
  17463. * Gets a string idenfifying the name of the class
  17464. * @returns "Node" string
  17465. */
  17466. Node.prototype.getClassName = function () {
  17467. return "Node";
  17468. };
  17469. Object.defineProperty(Node.prototype, "onDispose", {
  17470. /**
  17471. * Sets a callback that will be raised when the node will be disposed
  17472. */
  17473. set: function (callback) {
  17474. if (this._onDisposeObserver) {
  17475. this.onDisposeObservable.remove(this._onDisposeObserver);
  17476. }
  17477. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17478. },
  17479. enumerable: true,
  17480. configurable: true
  17481. });
  17482. /**
  17483. * Gets the scene of the node
  17484. * @returns a {BABYLON.Scene}
  17485. */
  17486. Node.prototype.getScene = function () {
  17487. return this._scene;
  17488. };
  17489. /**
  17490. * Gets the engine of the node
  17491. * @returns a {BABYLON.Engine}
  17492. */
  17493. Node.prototype.getEngine = function () {
  17494. return this._scene.getEngine();
  17495. };
  17496. /**
  17497. * Attach a behavior to the node
  17498. * @see http://doc.babylonjs.com/features/behaviour
  17499. * @param behavior defines the behavior to attach
  17500. * @returns the current Node
  17501. */
  17502. Node.prototype.addBehavior = function (behavior) {
  17503. var _this = this;
  17504. var index = this._behaviors.indexOf(behavior);
  17505. if (index !== -1) {
  17506. return this;
  17507. }
  17508. behavior.init();
  17509. if (this._scene.isLoading) {
  17510. // We defer the attach when the scene will be loaded
  17511. var observer = this._scene.onDataLoadedObservable.add(function () {
  17512. behavior.attach(_this);
  17513. setTimeout(function () {
  17514. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17515. _this._scene.onDataLoadedObservable.remove(observer);
  17516. }, 0);
  17517. });
  17518. }
  17519. else {
  17520. behavior.attach(this);
  17521. }
  17522. this._behaviors.push(behavior);
  17523. return this;
  17524. };
  17525. /**
  17526. * Remove an attached behavior
  17527. * @see http://doc.babylonjs.com/features/behaviour
  17528. * @param behavior defines the behavior to attach
  17529. * @returns the current Node
  17530. */
  17531. Node.prototype.removeBehavior = function (behavior) {
  17532. var index = this._behaviors.indexOf(behavior);
  17533. if (index === -1) {
  17534. return this;
  17535. }
  17536. this._behaviors[index].detach();
  17537. this._behaviors.splice(index, 1);
  17538. return this;
  17539. };
  17540. Object.defineProperty(Node.prototype, "behaviors", {
  17541. /**
  17542. * Gets the list of attached behaviors
  17543. * @see http://doc.babylonjs.com/features/behaviour
  17544. */
  17545. get: function () {
  17546. return this._behaviors;
  17547. },
  17548. enumerable: true,
  17549. configurable: true
  17550. });
  17551. /**
  17552. * Gets an attached behavior by name
  17553. * @param name defines the name of the behavior to look for
  17554. * @see http://doc.babylonjs.com/features/behaviour
  17555. * @returns null if behavior was not found else the requested behavior
  17556. */
  17557. Node.prototype.getBehaviorByName = function (name) {
  17558. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17559. var behavior = _a[_i];
  17560. if (behavior.name === name) {
  17561. return behavior;
  17562. }
  17563. }
  17564. return null;
  17565. };
  17566. /**
  17567. * Returns the world matrix of the node
  17568. * @returns a matrix containing the node's world matrix
  17569. */
  17570. Node.prototype.getWorldMatrix = function () {
  17571. return BABYLON.Matrix.Identity();
  17572. };
  17573. /** @hidden */
  17574. Node.prototype._getWorldMatrixDeterminant = function () {
  17575. return 1;
  17576. };
  17577. // override it in derived class if you add new variables to the cache
  17578. // and call the parent class method
  17579. /** @hidden */
  17580. Node.prototype._initCache = function () {
  17581. this._cache = {};
  17582. this._cache.parent = undefined;
  17583. };
  17584. /** @hidden */
  17585. Node.prototype.updateCache = function (force) {
  17586. if (!force && this.isSynchronized())
  17587. return;
  17588. this._cache.parent = this.parent;
  17589. this._updateCache();
  17590. };
  17591. // override it in derived class if you add new variables to the cache
  17592. // and call the parent class method if !ignoreParentClass
  17593. /** @hidden */
  17594. Node.prototype._updateCache = function (ignoreParentClass) {
  17595. };
  17596. // override it in derived class if you add new variables to the cache
  17597. /** @hidden */
  17598. Node.prototype._isSynchronized = function () {
  17599. return true;
  17600. };
  17601. /** @hidden */
  17602. Node.prototype._markSyncedWithParent = function () {
  17603. if (this.parent) {
  17604. this._parentRenderId = this.parent._childRenderId;
  17605. }
  17606. };
  17607. /** @hidden */
  17608. Node.prototype.isSynchronizedWithParent = function () {
  17609. if (!this.parent) {
  17610. return true;
  17611. }
  17612. if (this._parentRenderId !== this.parent._childRenderId) {
  17613. return false;
  17614. }
  17615. return this.parent.isSynchronized();
  17616. };
  17617. /** @hidden */
  17618. Node.prototype.isSynchronized = function (updateCache) {
  17619. var check = this.hasNewParent();
  17620. check = check || !this.isSynchronizedWithParent();
  17621. check = check || !this._isSynchronized();
  17622. if (updateCache)
  17623. this.updateCache(true);
  17624. return !check;
  17625. };
  17626. /** @hidden */
  17627. Node.prototype.hasNewParent = function (update) {
  17628. if (this._cache.parent === this.parent)
  17629. return false;
  17630. if (update)
  17631. this._cache.parent = this.parent;
  17632. return true;
  17633. };
  17634. /**
  17635. * Is this node ready to be used/rendered
  17636. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17637. * @return true if the node is ready
  17638. */
  17639. Node.prototype.isReady = function (completeCheck) {
  17640. if (completeCheck === void 0) { completeCheck = false; }
  17641. return this._isReady;
  17642. };
  17643. /**
  17644. * Is this node enabled?
  17645. * 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
  17646. * @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
  17647. * @return whether this node (and its parent) is enabled
  17648. */
  17649. Node.prototype.isEnabled = function (checkAncestors) {
  17650. if (checkAncestors === void 0) { checkAncestors = true; }
  17651. if (checkAncestors === false) {
  17652. return this._isEnabled;
  17653. }
  17654. if (this._isEnabled === false) {
  17655. return false;
  17656. }
  17657. if (this.parent !== undefined && this.parent !== null) {
  17658. return this.parent.isEnabled(checkAncestors);
  17659. }
  17660. return true;
  17661. };
  17662. /**
  17663. * Set the enabled state of this node
  17664. * @param value defines the new enabled state
  17665. */
  17666. Node.prototype.setEnabled = function (value) {
  17667. this._isEnabled = value;
  17668. };
  17669. /**
  17670. * Is this node a descendant of the given node?
  17671. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17672. * @param ancestor defines the parent node to inspect
  17673. * @returns a boolean indicating if this node is a descendant of the given node
  17674. */
  17675. Node.prototype.isDescendantOf = function (ancestor) {
  17676. if (this.parent) {
  17677. if (this.parent === ancestor) {
  17678. return true;
  17679. }
  17680. return this.parent.isDescendantOf(ancestor);
  17681. }
  17682. return false;
  17683. };
  17684. /** @hidden */
  17685. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17686. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17687. if (!this._children) {
  17688. return;
  17689. }
  17690. for (var index = 0; index < this._children.length; index++) {
  17691. var item = this._children[index];
  17692. if (!predicate || predicate(item)) {
  17693. results.push(item);
  17694. }
  17695. if (!directDescendantsOnly) {
  17696. item._getDescendants(results, false, predicate);
  17697. }
  17698. }
  17699. };
  17700. /**
  17701. * Will return all nodes that have this node as ascendant
  17702. * @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
  17703. * @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
  17704. * @return all children nodes of all types
  17705. */
  17706. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17707. var results = new Array();
  17708. this._getDescendants(results, directDescendantsOnly, predicate);
  17709. return results;
  17710. };
  17711. /**
  17712. * Get all child-meshes of this node
  17713. * @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
  17714. * @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
  17715. * @returns an array of {BABYLON.AbstractMesh}
  17716. */
  17717. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17718. var results = [];
  17719. this._getDescendants(results, directDescendantsOnly, function (node) {
  17720. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17721. });
  17722. return results;
  17723. };
  17724. /**
  17725. * Get all child-transformNodes of this node
  17726. * @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
  17727. * @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
  17728. * @returns an array of {BABYLON.TransformNode}
  17729. */
  17730. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17731. var results = [];
  17732. this._getDescendants(results, directDescendantsOnly, function (node) {
  17733. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17734. });
  17735. return results;
  17736. };
  17737. /**
  17738. * Get all direct children of this node
  17739. * @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
  17740. * @returns an array of {BABYLON.Node}
  17741. */
  17742. Node.prototype.getChildren = function (predicate) {
  17743. return this.getDescendants(true, predicate);
  17744. };
  17745. /** @hidden */
  17746. Node.prototype._setReady = function (state) {
  17747. if (state === this._isReady) {
  17748. return;
  17749. }
  17750. if (!state) {
  17751. this._isReady = false;
  17752. return;
  17753. }
  17754. if (this.onReady) {
  17755. this.onReady(this);
  17756. }
  17757. this._isReady = true;
  17758. };
  17759. /**
  17760. * Get an animation by name
  17761. * @param name defines the name of the animation to look for
  17762. * @returns null if not found else the requested animation
  17763. */
  17764. Node.prototype.getAnimationByName = function (name) {
  17765. for (var i = 0; i < this.animations.length; i++) {
  17766. var animation = this.animations[i];
  17767. if (animation.name === name) {
  17768. return animation;
  17769. }
  17770. }
  17771. return null;
  17772. };
  17773. /**
  17774. * Creates an animation range for this node
  17775. * @param name defines the name of the range
  17776. * @param from defines the starting key
  17777. * @param to defines the end key
  17778. */
  17779. Node.prototype.createAnimationRange = function (name, from, to) {
  17780. // check name not already in use
  17781. if (!this._ranges[name]) {
  17782. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17783. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17784. if (this.animations[i]) {
  17785. this.animations[i].createRange(name, from, to);
  17786. }
  17787. }
  17788. }
  17789. };
  17790. /**
  17791. * Delete a specific animation range
  17792. * @param name defines the name of the range to delete
  17793. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17794. */
  17795. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17796. if (deleteFrames === void 0) { deleteFrames = true; }
  17797. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17798. if (this.animations[i]) {
  17799. this.animations[i].deleteRange(name, deleteFrames);
  17800. }
  17801. }
  17802. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17803. };
  17804. /**
  17805. * Get an animation range by name
  17806. * @param name defines the name of the animation range to look for
  17807. * @returns null if not found else the requested animation range
  17808. */
  17809. Node.prototype.getAnimationRange = function (name) {
  17810. return this._ranges[name];
  17811. };
  17812. /**
  17813. * Will start the animation sequence
  17814. * @param name defines the range frames for animation sequence
  17815. * @param loop defines if the animation should loop (false by default)
  17816. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17817. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17818. * @returns the object created for this animation. If range does not exist, it will return null
  17819. */
  17820. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17821. var range = this.getAnimationRange(name);
  17822. if (!range) {
  17823. return null;
  17824. }
  17825. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17826. };
  17827. /**
  17828. * Serialize animation ranges into a JSON compatible object
  17829. * @returns serialization object
  17830. */
  17831. Node.prototype.serializeAnimationRanges = function () {
  17832. var serializationRanges = [];
  17833. for (var name in this._ranges) {
  17834. var localRange = this._ranges[name];
  17835. if (!localRange) {
  17836. continue;
  17837. }
  17838. var range = {};
  17839. range.name = name;
  17840. range.from = localRange.from;
  17841. range.to = localRange.to;
  17842. serializationRanges.push(range);
  17843. }
  17844. return serializationRanges;
  17845. };
  17846. /**
  17847. * Computes the world matrix of the node
  17848. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17849. * @returns the world matrix
  17850. */
  17851. Node.prototype.computeWorldMatrix = function (force) {
  17852. return BABYLON.Matrix.Identity();
  17853. };
  17854. /**
  17855. * Releases resources associated with this node.
  17856. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17857. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17858. */
  17859. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17860. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17861. if (!doNotRecurse) {
  17862. var nodes = this.getDescendants(true);
  17863. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17864. var node = nodes_1[_i];
  17865. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17866. }
  17867. }
  17868. else {
  17869. var transformNodes = this.getChildTransformNodes(true);
  17870. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17871. var transformNode = transformNodes_1[_a];
  17872. transformNode.parent = null;
  17873. transformNode.computeWorldMatrix(true);
  17874. }
  17875. }
  17876. this.parent = null;
  17877. // Callback
  17878. this.onDisposeObservable.notifyObservers(this);
  17879. this.onDisposeObservable.clear();
  17880. // Behaviors
  17881. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17882. var behavior = _c[_b];
  17883. behavior.detach();
  17884. }
  17885. this._behaviors = [];
  17886. this._isDisposed = true;
  17887. };
  17888. /**
  17889. * Parse animation range data from a serialization object and store them into a given node
  17890. * @param node defines where to store the animation ranges
  17891. * @param parsedNode defines the serialization object to read data from
  17892. * @param scene defines the hosting scene
  17893. */
  17894. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17895. if (parsedNode.ranges) {
  17896. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17897. var data = parsedNode.ranges[index];
  17898. node.createAnimationRange(data.name, data.from, data.to);
  17899. }
  17900. }
  17901. };
  17902. __decorate([
  17903. BABYLON.serialize()
  17904. ], Node.prototype, "name", void 0);
  17905. __decorate([
  17906. BABYLON.serialize()
  17907. ], Node.prototype, "id", void 0);
  17908. __decorate([
  17909. BABYLON.serialize()
  17910. ], Node.prototype, "uniqueId", void 0);
  17911. __decorate([
  17912. BABYLON.serialize()
  17913. ], Node.prototype, "state", void 0);
  17914. __decorate([
  17915. BABYLON.serialize()
  17916. ], Node.prototype, "metadata", void 0);
  17917. return Node;
  17918. }());
  17919. BABYLON.Node = Node;
  17920. })(BABYLON || (BABYLON = {}));
  17921. //# sourceMappingURL=babylon.node.js.map
  17922. var BABYLON;
  17923. (function (BABYLON) {
  17924. var BoundingSphere = /** @class */ (function () {
  17925. /**
  17926. * Creates a new bounding sphere
  17927. * @param min defines the minimum vector (in local space)
  17928. * @param max defines the maximum vector (in local space)
  17929. */
  17930. function BoundingSphere(min, max) {
  17931. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17932. this.reConstruct(min, max);
  17933. }
  17934. /**
  17935. * Recreates the entire bounding sphere from scratch
  17936. * @param min defines the new minimum vector (in local space)
  17937. * @param max defines the new maximum vector (in local space)
  17938. */
  17939. BoundingSphere.prototype.reConstruct = function (min, max) {
  17940. this.minimum = min.clone();
  17941. this.maximum = max.clone();
  17942. var distance = BABYLON.Vector3.Distance(min, max);
  17943. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17944. this.radius = distance * 0.5;
  17945. this.centerWorld = BABYLON.Vector3.Zero();
  17946. this._update(BABYLON.Matrix.Identity());
  17947. };
  17948. // Methods
  17949. BoundingSphere.prototype._update = function (world) {
  17950. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17951. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17952. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17953. };
  17954. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17955. for (var i = 0; i < 6; i++) {
  17956. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17957. return false;
  17958. }
  17959. return true;
  17960. };
  17961. BoundingSphere.prototype.intersectsPoint = function (point) {
  17962. var x = this.centerWorld.x - point.x;
  17963. var y = this.centerWorld.y - point.y;
  17964. var z = this.centerWorld.z - point.z;
  17965. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17966. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17967. return false;
  17968. return true;
  17969. };
  17970. // Statics
  17971. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17972. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17973. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17974. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17975. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17976. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17977. return false;
  17978. return true;
  17979. };
  17980. return BoundingSphere;
  17981. }());
  17982. BABYLON.BoundingSphere = BoundingSphere;
  17983. })(BABYLON || (BABYLON = {}));
  17984. //# sourceMappingURL=babylon.boundingSphere.js.map
  17985. var BABYLON;
  17986. (function (BABYLON) {
  17987. var BoundingBox = /** @class */ (function () {
  17988. /**
  17989. * Creates a new bounding box
  17990. * @param min defines the minimum vector (in local space)
  17991. * @param max defines the maximum vector (in local space)
  17992. */
  17993. function BoundingBox(min, max) {
  17994. this.vectorsWorld = new Array();
  17995. this.reConstruct(min, max);
  17996. }
  17997. // Methods
  17998. /**
  17999. * Recreates the entire bounding box from scratch
  18000. * @param min defines the new minimum vector (in local space)
  18001. * @param max defines the new maximum vector (in local space)
  18002. */
  18003. BoundingBox.prototype.reConstruct = function (min, max) {
  18004. this.minimum = min.clone();
  18005. this.maximum = max.clone();
  18006. // Bounding vectors
  18007. this.vectors = new Array();
  18008. this.vectors.push(this.minimum.clone());
  18009. this.vectors.push(this.maximum.clone());
  18010. this.vectors.push(this.minimum.clone());
  18011. this.vectors[2].x = this.maximum.x;
  18012. this.vectors.push(this.minimum.clone());
  18013. this.vectors[3].y = this.maximum.y;
  18014. this.vectors.push(this.minimum.clone());
  18015. this.vectors[4].z = this.maximum.z;
  18016. this.vectors.push(this.maximum.clone());
  18017. this.vectors[5].z = this.minimum.z;
  18018. this.vectors.push(this.maximum.clone());
  18019. this.vectors[6].x = this.minimum.x;
  18020. this.vectors.push(this.maximum.clone());
  18021. this.vectors[7].y = this.minimum.y;
  18022. // OBB
  18023. this.center = this.maximum.add(this.minimum).scale(0.5);
  18024. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18025. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18026. // World
  18027. for (var index = 0; index < this.vectors.length; index++) {
  18028. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18029. }
  18030. this.minimumWorld = BABYLON.Vector3.Zero();
  18031. this.maximumWorld = BABYLON.Vector3.Zero();
  18032. this.centerWorld = BABYLON.Vector3.Zero();
  18033. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18034. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18035. };
  18036. BoundingBox.prototype.getWorldMatrix = function () {
  18037. return this._worldMatrix;
  18038. };
  18039. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18040. this._worldMatrix.copyFrom(matrix);
  18041. return this;
  18042. };
  18043. BoundingBox.prototype._update = function (world) {
  18044. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18045. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18046. for (var index = 0; index < this.vectors.length; index++) {
  18047. var v = this.vectorsWorld[index];
  18048. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18049. if (v.x < this.minimumWorld.x)
  18050. this.minimumWorld.x = v.x;
  18051. if (v.y < this.minimumWorld.y)
  18052. this.minimumWorld.y = v.y;
  18053. if (v.z < this.minimumWorld.z)
  18054. this.minimumWorld.z = v.z;
  18055. if (v.x > this.maximumWorld.x)
  18056. this.maximumWorld.x = v.x;
  18057. if (v.y > this.maximumWorld.y)
  18058. this.maximumWorld.y = v.y;
  18059. if (v.z > this.maximumWorld.z)
  18060. this.maximumWorld.z = v.z;
  18061. }
  18062. // Extend
  18063. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18064. this.extendSizeWorld.scaleInPlace(0.5);
  18065. // OBB
  18066. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18067. this.centerWorld.scaleInPlace(0.5);
  18068. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18069. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18070. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18071. this._worldMatrix = world;
  18072. };
  18073. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18074. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18075. };
  18076. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18077. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18078. };
  18079. BoundingBox.prototype.intersectsPoint = function (point) {
  18080. var delta = -BABYLON.Epsilon;
  18081. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18082. return false;
  18083. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18084. return false;
  18085. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18086. return false;
  18087. return true;
  18088. };
  18089. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18090. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18091. };
  18092. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18093. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18094. return false;
  18095. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18096. return false;
  18097. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18098. return false;
  18099. return true;
  18100. };
  18101. // Statics
  18102. BoundingBox.Intersects = function (box0, box1) {
  18103. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18104. return false;
  18105. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18106. return false;
  18107. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18108. return false;
  18109. return true;
  18110. };
  18111. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18112. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18113. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18114. return (num <= (sphereRadius * sphereRadius));
  18115. };
  18116. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18117. for (var p = 0; p < 6; p++) {
  18118. for (var i = 0; i < 8; i++) {
  18119. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18120. return false;
  18121. }
  18122. }
  18123. }
  18124. return true;
  18125. };
  18126. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18127. for (var p = 0; p < 6; p++) {
  18128. var inCount = 8;
  18129. for (var i = 0; i < 8; i++) {
  18130. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18131. --inCount;
  18132. }
  18133. else {
  18134. break;
  18135. }
  18136. }
  18137. if (inCount === 0)
  18138. return false;
  18139. }
  18140. return true;
  18141. };
  18142. return BoundingBox;
  18143. }());
  18144. BABYLON.BoundingBox = BoundingBox;
  18145. })(BABYLON || (BABYLON = {}));
  18146. //# sourceMappingURL=babylon.boundingBox.js.map
  18147. var BABYLON;
  18148. (function (BABYLON) {
  18149. var computeBoxExtents = function (axis, box) {
  18150. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18151. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18152. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18153. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18154. var r = r0 + r1 + r2;
  18155. return {
  18156. min: p - r,
  18157. max: p + r
  18158. };
  18159. };
  18160. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18161. var axisOverlap = function (axis, box0, box1) {
  18162. var result0 = computeBoxExtents(axis, box0);
  18163. var result1 = computeBoxExtents(axis, box1);
  18164. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18165. };
  18166. var BoundingInfo = /** @class */ (function () {
  18167. function BoundingInfo(minimum, maximum) {
  18168. this.minimum = minimum;
  18169. this.maximum = maximum;
  18170. this._isLocked = false;
  18171. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18172. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18173. }
  18174. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18175. get: function () {
  18176. return this._isLocked;
  18177. },
  18178. set: function (value) {
  18179. this._isLocked = value;
  18180. },
  18181. enumerable: true,
  18182. configurable: true
  18183. });
  18184. // Methods
  18185. BoundingInfo.prototype.update = function (world) {
  18186. if (this._isLocked) {
  18187. return;
  18188. }
  18189. this.boundingBox._update(world);
  18190. this.boundingSphere._update(world);
  18191. };
  18192. /**
  18193. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18194. * @param center New center of the bounding info
  18195. * @param extend New extend of the bounding info
  18196. */
  18197. BoundingInfo.prototype.centerOn = function (center, extend) {
  18198. this.minimum = center.subtract(extend);
  18199. this.maximum = center.add(extend);
  18200. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18201. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18202. return this;
  18203. };
  18204. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18205. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18206. return false;
  18207. return this.boundingBox.isInFrustum(frustumPlanes);
  18208. };
  18209. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18210. /**
  18211. * Gets the world distance between the min and max points of the bounding box
  18212. */
  18213. get: function () {
  18214. var boundingBox = this.boundingBox;
  18215. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18216. return size.length();
  18217. },
  18218. enumerable: true,
  18219. configurable: true
  18220. });
  18221. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18222. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18223. };
  18224. BoundingInfo.prototype._checkCollision = function (collider) {
  18225. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18226. };
  18227. BoundingInfo.prototype.intersectsPoint = function (point) {
  18228. if (!this.boundingSphere.centerWorld) {
  18229. return false;
  18230. }
  18231. if (!this.boundingSphere.intersectsPoint(point)) {
  18232. return false;
  18233. }
  18234. if (!this.boundingBox.intersectsPoint(point)) {
  18235. return false;
  18236. }
  18237. return true;
  18238. };
  18239. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18240. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18241. return false;
  18242. }
  18243. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18244. return false;
  18245. }
  18246. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18247. return false;
  18248. }
  18249. if (!precise) {
  18250. return true;
  18251. }
  18252. var box0 = this.boundingBox;
  18253. var box1 = boundingInfo.boundingBox;
  18254. if (!axisOverlap(box0.directions[0], box0, box1))
  18255. return false;
  18256. if (!axisOverlap(box0.directions[1], box0, box1))
  18257. return false;
  18258. if (!axisOverlap(box0.directions[2], box0, box1))
  18259. return false;
  18260. if (!axisOverlap(box1.directions[0], box0, box1))
  18261. return false;
  18262. if (!axisOverlap(box1.directions[1], box0, box1))
  18263. return false;
  18264. if (!axisOverlap(box1.directions[2], box0, box1))
  18265. return false;
  18266. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18267. return false;
  18268. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18269. return false;
  18270. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18271. return false;
  18272. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18273. return false;
  18274. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18275. return false;
  18276. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18277. return false;
  18278. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18279. return false;
  18280. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18281. return false;
  18282. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18283. return false;
  18284. return true;
  18285. };
  18286. return BoundingInfo;
  18287. }());
  18288. BABYLON.BoundingInfo = BoundingInfo;
  18289. })(BABYLON || (BABYLON = {}));
  18290. //# sourceMappingURL=babylon.boundingInfo.js.map
  18291. var BABYLON;
  18292. (function (BABYLON) {
  18293. var TransformNode = /** @class */ (function (_super) {
  18294. __extends(TransformNode, _super);
  18295. function TransformNode(name, scene, isPure) {
  18296. if (scene === void 0) { scene = null; }
  18297. if (isPure === void 0) { isPure = true; }
  18298. var _this = _super.call(this, name, scene) || this;
  18299. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18300. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18301. _this._up = new BABYLON.Vector3(0, 1, 0);
  18302. _this._right = new BABYLON.Vector3(1, 0, 0);
  18303. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18304. // Properties
  18305. _this._rotation = BABYLON.Vector3.Zero();
  18306. _this._scaling = BABYLON.Vector3.One();
  18307. _this._isDirty = false;
  18308. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18309. _this.scalingDeterminant = 1;
  18310. _this.infiniteDistance = false;
  18311. _this.position = BABYLON.Vector3.Zero();
  18312. _this._localWorld = BABYLON.Matrix.Zero();
  18313. _this._worldMatrix = BABYLON.Matrix.Zero();
  18314. _this._worldMatrixDeterminant = 0;
  18315. _this._absolutePosition = BABYLON.Vector3.Zero();
  18316. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18317. _this._postMultiplyPivotMatrix = false;
  18318. _this._isWorldMatrixFrozen = false;
  18319. /**
  18320. * An event triggered after the world matrix is updated
  18321. */
  18322. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18323. _this._nonUniformScaling = false;
  18324. if (isPure) {
  18325. _this.getScene().addTransformNode(_this);
  18326. }
  18327. return _this;
  18328. }
  18329. /**
  18330. * Gets a string idenfifying the name of the class
  18331. * @returns "TransformNode" string
  18332. */
  18333. TransformNode.prototype.getClassName = function () {
  18334. return "TransformNode";
  18335. };
  18336. Object.defineProperty(TransformNode.prototype, "rotation", {
  18337. /**
  18338. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18339. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18340. * Default : (0.0, 0.0, 0.0)
  18341. */
  18342. get: function () {
  18343. return this._rotation;
  18344. },
  18345. set: function (newRotation) {
  18346. this._rotation = newRotation;
  18347. },
  18348. enumerable: true,
  18349. configurable: true
  18350. });
  18351. Object.defineProperty(TransformNode.prototype, "scaling", {
  18352. /**
  18353. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18354. * Default : (1.0, 1.0, 1.0)
  18355. */
  18356. get: function () {
  18357. return this._scaling;
  18358. },
  18359. /**
  18360. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18361. * Default : (1.0, 1.0, 1.0)
  18362. */
  18363. set: function (newScaling) {
  18364. this._scaling = newScaling;
  18365. },
  18366. enumerable: true,
  18367. configurable: true
  18368. });
  18369. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18370. /**
  18371. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18372. * It's null by default.
  18373. * 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)
  18374. */
  18375. get: function () {
  18376. return this._rotationQuaternion;
  18377. },
  18378. set: function (quaternion) {
  18379. this._rotationQuaternion = quaternion;
  18380. //reset the rotation vector.
  18381. if (quaternion && this.rotation.length()) {
  18382. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18383. }
  18384. },
  18385. enumerable: true,
  18386. configurable: true
  18387. });
  18388. Object.defineProperty(TransformNode.prototype, "forward", {
  18389. /**
  18390. * The forward direction of that transform in world space.
  18391. */
  18392. get: function () {
  18393. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18394. },
  18395. enumerable: true,
  18396. configurable: true
  18397. });
  18398. Object.defineProperty(TransformNode.prototype, "up", {
  18399. /**
  18400. * The up direction of that transform in world space.
  18401. */
  18402. get: function () {
  18403. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18404. },
  18405. enumerable: true,
  18406. configurable: true
  18407. });
  18408. Object.defineProperty(TransformNode.prototype, "right", {
  18409. /**
  18410. * The right direction of that transform in world space.
  18411. */
  18412. get: function () {
  18413. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18414. },
  18415. enumerable: true,
  18416. configurable: true
  18417. });
  18418. /**
  18419. * Returns the latest update of the World matrix
  18420. * Returns a Matrix.
  18421. */
  18422. TransformNode.prototype.getWorldMatrix = function () {
  18423. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18424. this.computeWorldMatrix();
  18425. }
  18426. return this._worldMatrix;
  18427. };
  18428. /** @hidden */
  18429. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18430. return this._worldMatrixDeterminant;
  18431. };
  18432. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18433. /**
  18434. * Returns directly the latest state of the mesh World matrix.
  18435. * A Matrix is returned.
  18436. */
  18437. get: function () {
  18438. return this._worldMatrix;
  18439. },
  18440. enumerable: true,
  18441. configurable: true
  18442. });
  18443. /**
  18444. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18445. * Returns the TransformNode.
  18446. */
  18447. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18448. this._poseMatrix.copyFrom(matrix);
  18449. return this;
  18450. };
  18451. /**
  18452. * Returns the mesh Pose matrix.
  18453. * Returned object : Matrix
  18454. */
  18455. TransformNode.prototype.getPoseMatrix = function () {
  18456. return this._poseMatrix;
  18457. };
  18458. TransformNode.prototype._isSynchronized = function () {
  18459. if (this._isDirty) {
  18460. return false;
  18461. }
  18462. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18463. return false;
  18464. if (this._cache.pivotMatrixUpdated) {
  18465. return false;
  18466. }
  18467. if (this.infiniteDistance) {
  18468. return false;
  18469. }
  18470. if (!this._cache.position.equals(this.position))
  18471. return false;
  18472. if (this.rotationQuaternion) {
  18473. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18474. return false;
  18475. }
  18476. if (!this._cache.rotation.equals(this.rotation))
  18477. return false;
  18478. if (!this._cache.scaling.equals(this.scaling))
  18479. return false;
  18480. return true;
  18481. };
  18482. TransformNode.prototype._initCache = function () {
  18483. _super.prototype._initCache.call(this);
  18484. this._cache.localMatrixUpdated = false;
  18485. this._cache.position = BABYLON.Vector3.Zero();
  18486. this._cache.scaling = BABYLON.Vector3.Zero();
  18487. this._cache.rotation = BABYLON.Vector3.Zero();
  18488. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18489. this._cache.billboardMode = -1;
  18490. };
  18491. TransformNode.prototype.markAsDirty = function (property) {
  18492. if (property === "rotation") {
  18493. this.rotationQuaternion = null;
  18494. }
  18495. this._currentRenderId = Number.MAX_VALUE;
  18496. this._isDirty = true;
  18497. return this;
  18498. };
  18499. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18500. /**
  18501. * Returns the current mesh absolute position.
  18502. * Retuns a Vector3.
  18503. */
  18504. get: function () {
  18505. return this._absolutePosition;
  18506. },
  18507. enumerable: true,
  18508. configurable: true
  18509. });
  18510. /**
  18511. * Sets a new matrix to apply before all other transformation
  18512. * @param matrix defines the transform matrix
  18513. * @returns the current TransformNode
  18514. */
  18515. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18516. return this.setPivotMatrix(matrix, false);
  18517. };
  18518. /**
  18519. * Sets a new pivot matrix to the current node
  18520. * @param matrix defines the new pivot matrix to use
  18521. * @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
  18522. * @returns the current TransformNode
  18523. */
  18524. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18525. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18526. this._pivotMatrix = matrix.clone();
  18527. this._cache.pivotMatrixUpdated = true;
  18528. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18529. if (this._postMultiplyPivotMatrix) {
  18530. if (!this._pivotMatrixInverse) {
  18531. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18532. }
  18533. else {
  18534. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18535. }
  18536. }
  18537. return this;
  18538. };
  18539. /**
  18540. * Returns the mesh pivot matrix.
  18541. * Default : Identity.
  18542. * A Matrix is returned.
  18543. */
  18544. TransformNode.prototype.getPivotMatrix = function () {
  18545. return this._pivotMatrix;
  18546. };
  18547. /**
  18548. * Prevents the World matrix to be computed any longer.
  18549. * Returns the TransformNode.
  18550. */
  18551. TransformNode.prototype.freezeWorldMatrix = function () {
  18552. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18553. this.computeWorldMatrix(true);
  18554. this._isWorldMatrixFrozen = true;
  18555. return this;
  18556. };
  18557. /**
  18558. * Allows back the World matrix computation.
  18559. * Returns the TransformNode.
  18560. */
  18561. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18562. this._isWorldMatrixFrozen = false;
  18563. this.computeWorldMatrix(true);
  18564. return this;
  18565. };
  18566. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18567. /**
  18568. * True if the World matrix has been frozen.
  18569. * Returns a boolean.
  18570. */
  18571. get: function () {
  18572. return this._isWorldMatrixFrozen;
  18573. },
  18574. enumerable: true,
  18575. configurable: true
  18576. });
  18577. /**
  18578. * Retuns the mesh absolute position in the World.
  18579. * Returns a Vector3.
  18580. */
  18581. TransformNode.prototype.getAbsolutePosition = function () {
  18582. this.computeWorldMatrix();
  18583. return this._absolutePosition;
  18584. };
  18585. /**
  18586. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18587. * Returns the TransformNode.
  18588. */
  18589. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18590. if (!absolutePosition) {
  18591. return this;
  18592. }
  18593. var absolutePositionX;
  18594. var absolutePositionY;
  18595. var absolutePositionZ;
  18596. if (absolutePosition.x === undefined) {
  18597. if (arguments.length < 3) {
  18598. return this;
  18599. }
  18600. absolutePositionX = arguments[0];
  18601. absolutePositionY = arguments[1];
  18602. absolutePositionZ = arguments[2];
  18603. }
  18604. else {
  18605. absolutePositionX = absolutePosition.x;
  18606. absolutePositionY = absolutePosition.y;
  18607. absolutePositionZ = absolutePosition.z;
  18608. }
  18609. if (this.parent) {
  18610. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18611. invertParentWorldMatrix.invert();
  18612. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18613. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18614. }
  18615. else {
  18616. this.position.x = absolutePositionX;
  18617. this.position.y = absolutePositionY;
  18618. this.position.z = absolutePositionZ;
  18619. }
  18620. return this;
  18621. };
  18622. /**
  18623. * Sets the mesh position in its local space.
  18624. * Returns the TransformNode.
  18625. */
  18626. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18627. this.computeWorldMatrix();
  18628. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18629. return this;
  18630. };
  18631. /**
  18632. * Returns the mesh position in the local space from the current World matrix values.
  18633. * Returns a new Vector3.
  18634. */
  18635. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18636. this.computeWorldMatrix();
  18637. var invLocalWorldMatrix = this._localWorld.clone();
  18638. invLocalWorldMatrix.invert();
  18639. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18640. };
  18641. /**
  18642. * Translates the mesh along the passed Vector3 in its local space.
  18643. * Returns the TransformNode.
  18644. */
  18645. TransformNode.prototype.locallyTranslate = function (vector3) {
  18646. this.computeWorldMatrix(true);
  18647. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18648. return this;
  18649. };
  18650. /**
  18651. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18652. * @param targetPoint the position (must be in same space as current mesh) to look at
  18653. * @param yawCor optional yaw (y-axis) correction in radians
  18654. * @param pitchCor optional pitch (x-axis) correction in radians
  18655. * @param rollCor optional roll (z-axis) correction in radians
  18656. * @param space the choosen space of the target
  18657. * @returns the TransformNode.
  18658. */
  18659. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18660. if (yawCor === void 0) { yawCor = 0; }
  18661. if (pitchCor === void 0) { pitchCor = 0; }
  18662. if (rollCor === void 0) { rollCor = 0; }
  18663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18664. var dv = TransformNode._lookAtVectorCache;
  18665. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18666. targetPoint.subtractToRef(pos, dv);
  18667. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18668. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18669. var pitch = Math.atan2(dv.y, len);
  18670. if (this.rotationQuaternion) {
  18671. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18672. }
  18673. else {
  18674. this.rotation.x = pitch + pitchCor;
  18675. this.rotation.y = yaw + yawCor;
  18676. this.rotation.z = rollCor;
  18677. }
  18678. return this;
  18679. };
  18680. /**
  18681. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18682. * This Vector3 is expressed in the World space.
  18683. */
  18684. TransformNode.prototype.getDirection = function (localAxis) {
  18685. var result = BABYLON.Vector3.Zero();
  18686. this.getDirectionToRef(localAxis, result);
  18687. return result;
  18688. };
  18689. /**
  18690. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18691. * localAxis is expressed in the mesh local space.
  18692. * result is computed in the Wordl space from the mesh World matrix.
  18693. * Returns the TransformNode.
  18694. */
  18695. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18696. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18697. return this;
  18698. };
  18699. /**
  18700. * Sets a new pivot point to the current node
  18701. * @param point defines the new pivot point to use
  18702. * @param space defines if the point is in world or local space (local by default)
  18703. * @returns the current TransformNode
  18704. */
  18705. TransformNode.prototype.setPivotPoint = function (point, space) {
  18706. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18707. if (this.getScene().getRenderId() == 0) {
  18708. this.computeWorldMatrix(true);
  18709. }
  18710. var wm = this.getWorldMatrix();
  18711. if (space == BABYLON.Space.WORLD) {
  18712. var tmat = BABYLON.Tmp.Matrix[0];
  18713. wm.invertToRef(tmat);
  18714. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18715. }
  18716. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18717. };
  18718. /**
  18719. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18720. */
  18721. TransformNode.prototype.getPivotPoint = function () {
  18722. var point = BABYLON.Vector3.Zero();
  18723. this.getPivotPointToRef(point);
  18724. return point;
  18725. };
  18726. /**
  18727. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18728. * Returns the TransformNode.
  18729. */
  18730. TransformNode.prototype.getPivotPointToRef = function (result) {
  18731. result.x = -this._pivotMatrix.m[12];
  18732. result.y = -this._pivotMatrix.m[13];
  18733. result.z = -this._pivotMatrix.m[14];
  18734. return this;
  18735. };
  18736. /**
  18737. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18738. */
  18739. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18740. var point = BABYLON.Vector3.Zero();
  18741. this.getAbsolutePivotPointToRef(point);
  18742. return point;
  18743. };
  18744. /**
  18745. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18746. * Returns the TransformNode.
  18747. */
  18748. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18749. result.x = this._pivotMatrix.m[12];
  18750. result.y = this._pivotMatrix.m[13];
  18751. result.z = this._pivotMatrix.m[14];
  18752. this.getPivotPointToRef(result);
  18753. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18754. return this;
  18755. };
  18756. /**
  18757. * Defines the passed node as the parent of the current node.
  18758. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18759. * Returns the TransformNode.
  18760. */
  18761. TransformNode.prototype.setParent = function (node) {
  18762. if (node === null) {
  18763. var rotation = BABYLON.Tmp.Quaternion[0];
  18764. var position = BABYLON.Tmp.Vector3[0];
  18765. var scale = BABYLON.Tmp.Vector3[1];
  18766. if (this.parent && this.parent.computeWorldMatrix) {
  18767. this.parent.computeWorldMatrix(true);
  18768. }
  18769. this.computeWorldMatrix(true);
  18770. this.getWorldMatrix().decompose(scale, rotation, position);
  18771. if (this.rotationQuaternion) {
  18772. this.rotationQuaternion.copyFrom(rotation);
  18773. }
  18774. else {
  18775. rotation.toEulerAnglesToRef(this.rotation);
  18776. }
  18777. this.scaling.x = scale.x;
  18778. this.scaling.y = scale.y;
  18779. this.scaling.z = scale.z;
  18780. this.position.x = position.x;
  18781. this.position.y = position.y;
  18782. this.position.z = position.z;
  18783. }
  18784. else {
  18785. var rotation = BABYLON.Tmp.Quaternion[0];
  18786. var position = BABYLON.Tmp.Vector3[0];
  18787. var scale = BABYLON.Tmp.Vector3[1];
  18788. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18789. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18790. this.computeWorldMatrix(true);
  18791. node.computeWorldMatrix(true);
  18792. node.getWorldMatrix().invertToRef(invParentMatrix);
  18793. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18794. diffMatrix.decompose(scale, rotation, position);
  18795. if (this.rotationQuaternion) {
  18796. this.rotationQuaternion.copyFrom(rotation);
  18797. }
  18798. else {
  18799. rotation.toEulerAnglesToRef(this.rotation);
  18800. }
  18801. this.position.x = position.x;
  18802. this.position.y = position.y;
  18803. this.position.z = position.z;
  18804. this.scaling.x = scale.x;
  18805. this.scaling.y = scale.y;
  18806. this.scaling.z = scale.z;
  18807. }
  18808. this.parent = node;
  18809. return this;
  18810. };
  18811. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18812. get: function () {
  18813. return this._nonUniformScaling;
  18814. },
  18815. enumerable: true,
  18816. configurable: true
  18817. });
  18818. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18819. if (this._nonUniformScaling === value) {
  18820. return false;
  18821. }
  18822. this._nonUniformScaling = true;
  18823. return true;
  18824. };
  18825. /**
  18826. * Attach the current TransformNode to another TransformNode associated with a bone
  18827. * @param bone Bone affecting the TransformNode
  18828. * @param affectedTransformNode TransformNode associated with the bone
  18829. */
  18830. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18831. this._transformToBoneReferal = affectedTransformNode;
  18832. this.parent = bone;
  18833. if (bone.getWorldMatrix().determinant() < 0) {
  18834. this.scalingDeterminant *= -1;
  18835. }
  18836. return this;
  18837. };
  18838. TransformNode.prototype.detachFromBone = function () {
  18839. if (!this.parent) {
  18840. return this;
  18841. }
  18842. if (this.parent.getWorldMatrix().determinant() < 0) {
  18843. this.scalingDeterminant *= -1;
  18844. }
  18845. this._transformToBoneReferal = null;
  18846. this.parent = null;
  18847. return this;
  18848. };
  18849. /**
  18850. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18851. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18852. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18853. * The passed axis is also normalized.
  18854. * Returns the TransformNode.
  18855. */
  18856. TransformNode.prototype.rotate = function (axis, amount, space) {
  18857. axis.normalize();
  18858. if (!this.rotationQuaternion) {
  18859. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18860. this.rotation = BABYLON.Vector3.Zero();
  18861. }
  18862. var rotationQuaternion;
  18863. if (!space || space === BABYLON.Space.LOCAL) {
  18864. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18865. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18866. }
  18867. else {
  18868. if (this.parent) {
  18869. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18870. invertParentWorldMatrix.invert();
  18871. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18872. }
  18873. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18874. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18875. }
  18876. return this;
  18877. };
  18878. /**
  18879. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18880. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18881. * The passed axis is also normalized.
  18882. * Returns the TransformNode.
  18883. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18884. */
  18885. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18886. axis.normalize();
  18887. if (!this.rotationQuaternion) {
  18888. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18889. this.rotation.copyFromFloats(0, 0, 0);
  18890. }
  18891. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18892. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18893. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18894. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18895. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18896. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18897. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18898. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18899. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18900. return this;
  18901. };
  18902. /**
  18903. * Translates the mesh along the axis vector for the passed distance in the given space.
  18904. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18905. * Returns the TransformNode.
  18906. */
  18907. TransformNode.prototype.translate = function (axis, distance, space) {
  18908. var displacementVector = axis.scale(distance);
  18909. if (!space || space === BABYLON.Space.LOCAL) {
  18910. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18911. this.setPositionWithLocalVector(tempV3);
  18912. }
  18913. else {
  18914. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18915. }
  18916. return this;
  18917. };
  18918. /**
  18919. * Adds a rotation step to the mesh current rotation.
  18920. * x, y, z are Euler angles expressed in radians.
  18921. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18922. * This means this rotation is made in the mesh local space only.
  18923. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18924. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18925. * ```javascript
  18926. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18927. * ```
  18928. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18929. * 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.
  18930. * Returns the TransformNode.
  18931. */
  18932. TransformNode.prototype.addRotation = function (x, y, z) {
  18933. var rotationQuaternion;
  18934. if (this.rotationQuaternion) {
  18935. rotationQuaternion = this.rotationQuaternion;
  18936. }
  18937. else {
  18938. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18939. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18940. }
  18941. var accumulation = BABYLON.Tmp.Quaternion[0];
  18942. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18943. rotationQuaternion.multiplyInPlace(accumulation);
  18944. if (!this.rotationQuaternion) {
  18945. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18946. }
  18947. return this;
  18948. };
  18949. /**
  18950. * Computes the mesh World matrix and returns it.
  18951. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18952. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18953. * If the parameter `force`is set to `true`, the actual computation is done.
  18954. * Returns the mesh World Matrix.
  18955. */
  18956. TransformNode.prototype.computeWorldMatrix = function (force) {
  18957. if (this._isWorldMatrixFrozen) {
  18958. return this._worldMatrix;
  18959. }
  18960. if (!force && this.isSynchronized(true)) {
  18961. this._currentRenderId = this.getScene().getRenderId();
  18962. return this._worldMatrix;
  18963. }
  18964. this._cache.position.copyFrom(this.position);
  18965. this._cache.scaling.copyFrom(this.scaling);
  18966. this._cache.pivotMatrixUpdated = false;
  18967. this._cache.billboardMode = this.billboardMode;
  18968. this._currentRenderId = this.getScene().getRenderId();
  18969. this._childRenderId = this.getScene().getRenderId();
  18970. this._isDirty = false;
  18971. // Scaling
  18972. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18973. // Rotation
  18974. //rotate, if quaternion is set and rotation was used
  18975. if (this.rotationQuaternion) {
  18976. var len = this.rotation.length();
  18977. if (len) {
  18978. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18979. this.rotation.copyFromFloats(0, 0, 0);
  18980. }
  18981. }
  18982. if (this.rotationQuaternion) {
  18983. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18984. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18985. }
  18986. else {
  18987. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18988. this._cache.rotation.copyFrom(this.rotation);
  18989. }
  18990. // Translation
  18991. var camera = this.getScene().activeCamera;
  18992. if (this.infiniteDistance && !this.parent && camera) {
  18993. var cameraWorldMatrix = camera.getWorldMatrix();
  18994. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18995. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18996. }
  18997. else {
  18998. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18999. }
  19000. // Composing transformations
  19001. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19002. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19003. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19004. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19005. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19006. // Need to decompose each rotation here
  19007. var currentPosition = BABYLON.Tmp.Vector3[3];
  19008. if (this.parent && this.parent.getWorldMatrix) {
  19009. if (this._transformToBoneReferal) {
  19010. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19011. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19012. }
  19013. else {
  19014. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19015. }
  19016. }
  19017. else {
  19018. currentPosition.copyFrom(this.position);
  19019. }
  19020. currentPosition.subtractInPlace(camera.globalPosition);
  19021. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19022. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19023. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19024. }
  19025. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19026. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19027. }
  19028. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19029. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19030. }
  19031. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19032. }
  19033. else {
  19034. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19035. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19036. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19037. }
  19038. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19039. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19040. }
  19041. // Local world
  19042. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19043. // Parent
  19044. if (this.parent && this.parent.getWorldMatrix) {
  19045. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19046. if (this._transformToBoneReferal) {
  19047. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19048. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19049. }
  19050. else {
  19051. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19052. }
  19053. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19054. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19055. this._worldMatrix.copyFrom(this._localWorld);
  19056. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19057. }
  19058. else {
  19059. if (this._transformToBoneReferal) {
  19060. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19061. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19062. }
  19063. else {
  19064. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19065. }
  19066. }
  19067. this._markSyncedWithParent();
  19068. }
  19069. else {
  19070. this._worldMatrix.copyFrom(this._localWorld);
  19071. }
  19072. // Post multiply inverse of pivotMatrix
  19073. if (this._postMultiplyPivotMatrix) {
  19074. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19075. }
  19076. // Normal matrix
  19077. if (this.scaling.isNonUniform) {
  19078. this._updateNonUniformScalingState(true);
  19079. }
  19080. else if (this.parent && this.parent._nonUniformScaling) {
  19081. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19082. }
  19083. else {
  19084. this._updateNonUniformScalingState(false);
  19085. }
  19086. this._afterComputeWorldMatrix();
  19087. // Absolute position
  19088. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19089. // Callbacks
  19090. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19091. if (!this._poseMatrix) {
  19092. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19093. }
  19094. // Cache the determinant
  19095. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19096. return this._worldMatrix;
  19097. };
  19098. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19099. };
  19100. /**
  19101. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19102. * @param func: callback function to add
  19103. *
  19104. * Returns the TransformNode.
  19105. */
  19106. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19107. this.onAfterWorldMatrixUpdateObservable.add(func);
  19108. return this;
  19109. };
  19110. /**
  19111. * Removes a registered callback function.
  19112. * Returns the TransformNode.
  19113. */
  19114. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19115. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19116. return this;
  19117. };
  19118. /**
  19119. * Clone the current transform node
  19120. * Returns the new transform node
  19121. * @param name Name of the new clone
  19122. * @param newParent New parent for the clone
  19123. * @param doNotCloneChildren Do not clone children hierarchy
  19124. */
  19125. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19126. var _this = this;
  19127. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19128. result.name = name;
  19129. result.id = name;
  19130. if (newParent) {
  19131. result.parent = newParent;
  19132. }
  19133. if (!doNotCloneChildren) {
  19134. // Children
  19135. var directDescendants = this.getDescendants(true);
  19136. for (var index = 0; index < directDescendants.length; index++) {
  19137. var child = directDescendants[index];
  19138. if (child.clone) {
  19139. child.clone(name + "." + child.name, result);
  19140. }
  19141. }
  19142. }
  19143. return result;
  19144. };
  19145. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19146. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19147. serializationObject.type = this.getClassName();
  19148. // Parent
  19149. if (this.parent) {
  19150. serializationObject.parentId = this.parent.id;
  19151. }
  19152. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19153. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19154. }
  19155. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19156. serializationObject.isEnabled = this.isEnabled();
  19157. // Parent
  19158. if (this.parent) {
  19159. serializationObject.parentId = this.parent.id;
  19160. }
  19161. return serializationObject;
  19162. };
  19163. // Statics
  19164. /**
  19165. * Returns a new TransformNode object parsed from the source provided.
  19166. * The parameter `parsedMesh` is the source.
  19167. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19168. */
  19169. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19170. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19171. if (BABYLON.Tags) {
  19172. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19173. }
  19174. if (parsedTransformNode.localMatrix) {
  19175. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19176. }
  19177. else if (parsedTransformNode.pivotMatrix) {
  19178. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19179. }
  19180. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19181. // Parent
  19182. if (parsedTransformNode.parentId) {
  19183. transformNode._waitingParentId = parsedTransformNode.parentId;
  19184. }
  19185. return transformNode;
  19186. };
  19187. /**
  19188. * Releases resources associated with this transform node.
  19189. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19190. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19191. */
  19192. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19193. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19194. // Animations
  19195. this.getScene().stopAnimation(this);
  19196. // Remove from scene
  19197. this.getScene().removeTransformNode(this);
  19198. this.onAfterWorldMatrixUpdateObservable.clear();
  19199. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19200. };
  19201. // Statics
  19202. TransformNode.BILLBOARDMODE_NONE = 0;
  19203. TransformNode.BILLBOARDMODE_X = 1;
  19204. TransformNode.BILLBOARDMODE_Y = 2;
  19205. TransformNode.BILLBOARDMODE_Z = 4;
  19206. TransformNode.BILLBOARDMODE_ALL = 7;
  19207. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19208. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19209. __decorate([
  19210. BABYLON.serializeAsVector3()
  19211. ], TransformNode.prototype, "_rotation", void 0);
  19212. __decorate([
  19213. BABYLON.serializeAsQuaternion()
  19214. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19215. __decorate([
  19216. BABYLON.serializeAsVector3()
  19217. ], TransformNode.prototype, "_scaling", void 0);
  19218. __decorate([
  19219. BABYLON.serialize()
  19220. ], TransformNode.prototype, "billboardMode", void 0);
  19221. __decorate([
  19222. BABYLON.serialize()
  19223. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19224. __decorate([
  19225. BABYLON.serialize()
  19226. ], TransformNode.prototype, "infiniteDistance", void 0);
  19227. __decorate([
  19228. BABYLON.serializeAsVector3()
  19229. ], TransformNode.prototype, "position", void 0);
  19230. return TransformNode;
  19231. }(BABYLON.Node));
  19232. BABYLON.TransformNode = TransformNode;
  19233. })(BABYLON || (BABYLON = {}));
  19234. //# sourceMappingURL=babylon.transformNode.js.map
  19235. var BABYLON;
  19236. (function (BABYLON) {
  19237. /**
  19238. * Class used to store all common mesh properties
  19239. */
  19240. var AbstractMesh = /** @class */ (function (_super) {
  19241. __extends(AbstractMesh, _super);
  19242. // Constructor
  19243. /**
  19244. * Creates a new AbstractMesh
  19245. * @param name defines the name of the mesh
  19246. * @param scene defines the hosting scene
  19247. */
  19248. function AbstractMesh(name, scene) {
  19249. if (scene === void 0) { scene = null; }
  19250. var _this = _super.call(this, name, scene, false) || this;
  19251. _this._facetNb = 0; // facet number
  19252. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19253. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19254. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19255. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19256. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19257. _this._subDiv = {
  19258. max: 1,
  19259. X: 1,
  19260. Y: 1,
  19261. Z: 1
  19262. };
  19263. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19264. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19265. // Events
  19266. /**
  19267. * An event triggered when this mesh collides with another one
  19268. */
  19269. _this.onCollideObservable = new BABYLON.Observable();
  19270. /**
  19271. * An event triggered when the collision's position changes
  19272. */
  19273. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19274. /**
  19275. * An event triggered when material is changed
  19276. */
  19277. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19278. // Properties
  19279. /**
  19280. * Gets or sets the orientation for POV movement & rotation
  19281. */
  19282. _this.definedFacingForward = true;
  19283. /**
  19284. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19285. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19286. * * 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.
  19287. * @see http://doc.babylonjs.com/features/occlusionquery
  19288. */
  19289. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19290. /**
  19291. * 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:
  19292. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19293. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19294. * * 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.
  19295. * @see http://doc.babylonjs.com/features/occlusionquery
  19296. */
  19297. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19298. /**
  19299. * 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.
  19300. * The default value is -1 which means don't break the query and wait till the result
  19301. * @see http://doc.babylonjs.com/features/occlusionquery
  19302. */
  19303. _this.occlusionRetryCount = -1;
  19304. _this._occlusionInternalRetryCounter = 0;
  19305. _this._isOccluded = false;
  19306. _this._isOcclusionQueryInProgress = false;
  19307. _this._visibility = 1.0;
  19308. /** Gets or sets the alpha index used to sort transparent meshes
  19309. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19310. */
  19311. _this.alphaIndex = Number.MAX_VALUE;
  19312. /**
  19313. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19314. */
  19315. _this.isVisible = true;
  19316. /**
  19317. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19318. */
  19319. _this.isPickable = true;
  19320. /**
  19321. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19322. */
  19323. _this.showBoundingBox = false;
  19324. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19325. _this.showSubMeshesBoundingBox = false;
  19326. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19327. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19328. */
  19329. _this.isBlocker = false;
  19330. /**
  19331. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19332. */
  19333. _this.enablePointerMoveEvents = false;
  19334. /**
  19335. * Specifies the rendering group id for this mesh (0 by default)
  19336. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19337. */
  19338. _this.renderingGroupId = 0;
  19339. _this._receiveShadows = false;
  19340. /**
  19341. * Gets or sets a boolean indicating if the outline must be rendered as well
  19342. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19343. */
  19344. _this.renderOutline = false;
  19345. /** Defines color to use when rendering outline */
  19346. _this.outlineColor = BABYLON.Color3.Red();
  19347. /** Define width to use when rendering outline */
  19348. _this.outlineWidth = 0.02;
  19349. /**
  19350. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19351. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19352. */
  19353. _this.renderOverlay = false;
  19354. /** Defines color to use when rendering overlay */
  19355. _this.overlayColor = BABYLON.Color3.Red();
  19356. /** Defines alpha to use when rendering overlay */
  19357. _this.overlayAlpha = 0.5;
  19358. _this._hasVertexAlpha = false;
  19359. _this._useVertexColors = true;
  19360. _this._computeBonesUsingShaders = true;
  19361. _this._numBoneInfluencers = 4;
  19362. _this._applyFog = true;
  19363. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19364. _this.useOctreeForRenderingSelection = true;
  19365. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19366. _this.useOctreeForPicking = true;
  19367. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19368. _this.useOctreeForCollisions = true;
  19369. _this._layerMask = 0x0FFFFFFF;
  19370. /**
  19371. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19372. */
  19373. _this.alwaysSelectAsActiveMesh = false;
  19374. /**
  19375. * Gets or sets the current action manager
  19376. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19377. */
  19378. _this.actionManager = null;
  19379. /**
  19380. * Gets or sets impostor used for physic simulation
  19381. * @see http://doc.babylonjs.com/features/physics_engine
  19382. */
  19383. _this.physicsImpostor = null;
  19384. // Collisions
  19385. _this._checkCollisions = false;
  19386. _this._collisionMask = -1;
  19387. _this._collisionGroup = -1;
  19388. /**
  19389. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19390. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19391. */
  19392. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19393. /**
  19394. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19395. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19396. */
  19397. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19398. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19399. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19400. // Edges
  19401. /**
  19402. * Defines edge width used when edgesRenderer is enabled
  19403. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19404. */
  19405. _this.edgesWidth = 1;
  19406. /**
  19407. * Defines edge color used when edgesRenderer is enabled
  19408. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19409. */
  19410. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19411. // Cache
  19412. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19413. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19414. /** @hidden */
  19415. _this._renderId = 0;
  19416. /** @hidden */
  19417. _this._intersectionsInProgress = new Array();
  19418. /** @hidden */
  19419. _this._unIndexed = false;
  19420. /** @hidden */
  19421. _this._lightSources = new Array();
  19422. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19423. if (collidedMesh === void 0) { collidedMesh = null; }
  19424. //TODO move this to the collision coordinator!
  19425. if (_this.getScene().workerCollisions)
  19426. newPosition.multiplyInPlace(_this._collider._radius);
  19427. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19428. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19429. _this.position.addInPlace(_this._diffPositionForCollisions);
  19430. }
  19431. if (collidedMesh) {
  19432. _this.onCollideObservable.notifyObservers(collidedMesh);
  19433. }
  19434. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19435. };
  19436. _this.getScene().addMesh(_this);
  19437. _this._resyncLightSources();
  19438. return _this;
  19439. }
  19440. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19441. /**
  19442. * No billboard
  19443. */
  19444. get: function () {
  19445. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19446. },
  19447. enumerable: true,
  19448. configurable: true
  19449. });
  19450. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19451. /** Billboard on X axis */
  19452. get: function () {
  19453. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19454. },
  19455. enumerable: true,
  19456. configurable: true
  19457. });
  19458. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19459. /** Billboard on Y axis */
  19460. get: function () {
  19461. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19467. /** Billboard on Z axis */
  19468. get: function () {
  19469. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19470. },
  19471. enumerable: true,
  19472. configurable: true
  19473. });
  19474. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19475. /** Billboard on all axes */
  19476. get: function () {
  19477. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19478. },
  19479. enumerable: true,
  19480. configurable: true
  19481. });
  19482. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19483. /**
  19484. * Gets the number of facets in the mesh
  19485. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19486. */
  19487. get: function () {
  19488. return this._facetNb;
  19489. },
  19490. enumerable: true,
  19491. configurable: true
  19492. });
  19493. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19494. /**
  19495. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19496. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19497. */
  19498. get: function () {
  19499. return this._partitioningSubdivisions;
  19500. },
  19501. set: function (nb) {
  19502. this._partitioningSubdivisions = nb;
  19503. },
  19504. enumerable: true,
  19505. configurable: true
  19506. });
  19507. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19508. /**
  19509. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19510. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19511. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19512. */
  19513. get: function () {
  19514. return this._partitioningBBoxRatio;
  19515. },
  19516. set: function (ratio) {
  19517. this._partitioningBBoxRatio = ratio;
  19518. },
  19519. enumerable: true,
  19520. configurable: true
  19521. });
  19522. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19523. /**
  19524. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19525. * Works only for updatable meshes.
  19526. * Doesn't work with multi-materials
  19527. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19528. */
  19529. get: function () {
  19530. return this._facetDepthSort;
  19531. },
  19532. set: function (sort) {
  19533. this._facetDepthSort = sort;
  19534. },
  19535. enumerable: true,
  19536. configurable: true
  19537. });
  19538. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19539. /**
  19540. * The location (Vector3) where the facet depth sort must be computed from.
  19541. * By default, the active camera position.
  19542. * Used only when facet depth sort is enabled
  19543. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19544. */
  19545. get: function () {
  19546. return this._facetDepthSortFrom;
  19547. },
  19548. set: function (location) {
  19549. this._facetDepthSortFrom = location;
  19550. },
  19551. enumerable: true,
  19552. configurable: true
  19553. });
  19554. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19555. /**
  19556. * gets a boolean indicating if facetData is enabled
  19557. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19558. */
  19559. get: function () {
  19560. return this._facetDataEnabled;
  19561. },
  19562. enumerable: true,
  19563. configurable: true
  19564. });
  19565. /** @hidden */
  19566. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19567. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19568. return false;
  19569. }
  19570. this._markSubMeshesAsMiscDirty();
  19571. return true;
  19572. };
  19573. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19574. /** Set a function to call when this mesh collides with another one */
  19575. set: function (callback) {
  19576. if (this._onCollideObserver) {
  19577. this.onCollideObservable.remove(this._onCollideObserver);
  19578. }
  19579. this._onCollideObserver = this.onCollideObservable.add(callback);
  19580. },
  19581. enumerable: true,
  19582. configurable: true
  19583. });
  19584. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19585. /** Set a function to call when the collision's position changes */
  19586. set: function (callback) {
  19587. if (this._onCollisionPositionChangeObserver) {
  19588. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19589. }
  19590. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19591. },
  19592. enumerable: true,
  19593. configurable: true
  19594. });
  19595. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19596. /**
  19597. * 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
  19598. * @see http://doc.babylonjs.com/features/occlusionquery
  19599. */
  19600. get: function () {
  19601. return this._isOccluded;
  19602. },
  19603. set: function (value) {
  19604. this._isOccluded = value;
  19605. },
  19606. enumerable: true,
  19607. configurable: true
  19608. });
  19609. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19610. /**
  19611. * Flag to check the progress status of the query
  19612. * @see http://doc.babylonjs.com/features/occlusionquery
  19613. */
  19614. get: function () {
  19615. return this._isOcclusionQueryInProgress;
  19616. },
  19617. enumerable: true,
  19618. configurable: true
  19619. });
  19620. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19621. /**
  19622. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19623. */
  19624. get: function () {
  19625. return this._visibility;
  19626. },
  19627. /**
  19628. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19629. */
  19630. set: function (value) {
  19631. if (this._visibility === value) {
  19632. return;
  19633. }
  19634. this._visibility = value;
  19635. this._markSubMeshesAsMiscDirty();
  19636. },
  19637. enumerable: true,
  19638. configurable: true
  19639. });
  19640. Object.defineProperty(AbstractMesh.prototype, "material", {
  19641. /** Gets or sets current material */
  19642. get: function () {
  19643. return this._material;
  19644. },
  19645. set: function (value) {
  19646. if (this._material === value) {
  19647. return;
  19648. }
  19649. this._material = value;
  19650. if (this.onMaterialChangedObservable.hasObservers) {
  19651. this.onMaterialChangedObservable.notifyObservers(this);
  19652. }
  19653. if (!this.subMeshes) {
  19654. return;
  19655. }
  19656. this._unBindEffect();
  19657. },
  19658. enumerable: true,
  19659. configurable: true
  19660. });
  19661. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19662. /**
  19663. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19664. * @see http://doc.babylonjs.com/babylon101/shadows
  19665. */
  19666. get: function () {
  19667. return this._receiveShadows;
  19668. },
  19669. set: function (value) {
  19670. if (this._receiveShadows === value) {
  19671. return;
  19672. }
  19673. this._receiveShadows = value;
  19674. this._markSubMeshesAsLightDirty();
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19680. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19681. get: function () {
  19682. return this._hasVertexAlpha;
  19683. },
  19684. set: function (value) {
  19685. if (this._hasVertexAlpha === value) {
  19686. return;
  19687. }
  19688. this._hasVertexAlpha = value;
  19689. this._markSubMeshesAsAttributesDirty();
  19690. this._markSubMeshesAsMiscDirty();
  19691. },
  19692. enumerable: true,
  19693. configurable: true
  19694. });
  19695. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19696. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19697. get: function () {
  19698. return this._useVertexColors;
  19699. },
  19700. set: function (value) {
  19701. if (this._useVertexColors === value) {
  19702. return;
  19703. }
  19704. this._useVertexColors = value;
  19705. this._markSubMeshesAsAttributesDirty();
  19706. },
  19707. enumerable: true,
  19708. configurable: true
  19709. });
  19710. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19711. /**
  19712. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19713. */
  19714. get: function () {
  19715. return this._computeBonesUsingShaders;
  19716. },
  19717. set: function (value) {
  19718. if (this._computeBonesUsingShaders === value) {
  19719. return;
  19720. }
  19721. this._computeBonesUsingShaders = value;
  19722. this._markSubMeshesAsAttributesDirty();
  19723. },
  19724. enumerable: true,
  19725. configurable: true
  19726. });
  19727. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19728. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19729. get: function () {
  19730. return this._numBoneInfluencers;
  19731. },
  19732. set: function (value) {
  19733. if (this._numBoneInfluencers === value) {
  19734. return;
  19735. }
  19736. this._numBoneInfluencers = value;
  19737. this._markSubMeshesAsAttributesDirty();
  19738. },
  19739. enumerable: true,
  19740. configurable: true
  19741. });
  19742. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19743. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19744. get: function () {
  19745. return this._applyFog;
  19746. },
  19747. set: function (value) {
  19748. if (this._applyFog === value) {
  19749. return;
  19750. }
  19751. this._applyFog = value;
  19752. this._markSubMeshesAsMiscDirty();
  19753. },
  19754. enumerable: true,
  19755. configurable: true
  19756. });
  19757. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19758. /**
  19759. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19760. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19761. */
  19762. get: function () {
  19763. return this._layerMask;
  19764. },
  19765. set: function (value) {
  19766. if (value === this._layerMask) {
  19767. return;
  19768. }
  19769. this._layerMask = value;
  19770. this._resyncLightSources();
  19771. },
  19772. enumerable: true,
  19773. configurable: true
  19774. });
  19775. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19776. /**
  19777. * Gets or sets a collision mask used to mask collisions (default is -1).
  19778. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19779. */
  19780. get: function () {
  19781. return this._collisionMask;
  19782. },
  19783. set: function (mask) {
  19784. this._collisionMask = !isNaN(mask) ? mask : -1;
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19790. /**
  19791. * Gets or sets the current collision group mask (-1 by default).
  19792. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19793. */
  19794. get: function () {
  19795. return this._collisionGroup;
  19796. },
  19797. set: function (mask) {
  19798. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19804. /** @hidden */
  19805. get: function () {
  19806. return null;
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19812. get: function () {
  19813. return this._skeleton;
  19814. },
  19815. /**
  19816. * Gets or sets a skeleton to apply skining transformations
  19817. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19818. */
  19819. set: function (value) {
  19820. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19821. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19822. }
  19823. if (value && value.needInitialSkinMatrix) {
  19824. value._registerMeshWithPoseMatrix(this);
  19825. }
  19826. this._skeleton = value;
  19827. if (!this._skeleton) {
  19828. this._bonesTransformMatrices = null;
  19829. }
  19830. this._markSubMeshesAsAttributesDirty();
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. /**
  19836. * Returns the string "AbstractMesh"
  19837. * @returns "AbstractMesh"
  19838. */
  19839. AbstractMesh.prototype.getClassName = function () {
  19840. return "AbstractMesh";
  19841. };
  19842. /**
  19843. * Gets a string representation of the current mesh
  19844. * @param fullDetails defines a boolean indicating if full details must be included
  19845. * @returns a string representation of the current mesh
  19846. */
  19847. AbstractMesh.prototype.toString = function (fullDetails) {
  19848. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19849. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19850. if (this._skeleton) {
  19851. ret += ", skeleton: " + this._skeleton.name;
  19852. }
  19853. if (fullDetails) {
  19854. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19855. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19856. }
  19857. return ret;
  19858. };
  19859. /** @hidden */
  19860. AbstractMesh.prototype._rebuild = function () {
  19861. if (this._occlusionQuery) {
  19862. this._occlusionQuery = null;
  19863. }
  19864. if (this._edgesRenderer) {
  19865. this._edgesRenderer._rebuild();
  19866. }
  19867. if (!this.subMeshes) {
  19868. return;
  19869. }
  19870. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19871. var subMesh = _a[_i];
  19872. subMesh._rebuild();
  19873. }
  19874. };
  19875. /** @hidden */
  19876. AbstractMesh.prototype._resyncLightSources = function () {
  19877. this._lightSources.length = 0;
  19878. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19879. var light = _a[_i];
  19880. if (!light.isEnabled()) {
  19881. continue;
  19882. }
  19883. if (light.canAffectMesh(this)) {
  19884. this._lightSources.push(light);
  19885. }
  19886. }
  19887. this._markSubMeshesAsLightDirty();
  19888. };
  19889. /** @hidden */
  19890. AbstractMesh.prototype._resyncLighSource = function (light) {
  19891. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19892. var index = this._lightSources.indexOf(light);
  19893. if (index === -1) {
  19894. if (!isIn) {
  19895. return;
  19896. }
  19897. this._lightSources.push(light);
  19898. }
  19899. else {
  19900. if (isIn) {
  19901. return;
  19902. }
  19903. this._lightSources.splice(index, 1);
  19904. }
  19905. this._markSubMeshesAsLightDirty();
  19906. };
  19907. /** @hidden */
  19908. AbstractMesh.prototype._unBindEffect = function () {
  19909. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19910. var subMesh = _a[_i];
  19911. subMesh.setEffect(null);
  19912. }
  19913. };
  19914. /** @hidden */
  19915. AbstractMesh.prototype._removeLightSource = function (light) {
  19916. var index = this._lightSources.indexOf(light);
  19917. if (index === -1) {
  19918. return;
  19919. }
  19920. this._lightSources.splice(index, 1);
  19921. this._markSubMeshesAsLightDirty();
  19922. };
  19923. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19924. if (!this.subMeshes) {
  19925. return;
  19926. }
  19927. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19928. var subMesh = _a[_i];
  19929. if (subMesh._materialDefines) {
  19930. func(subMesh._materialDefines);
  19931. }
  19932. }
  19933. };
  19934. /** @hidden */
  19935. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19936. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19937. };
  19938. /** @hidden */
  19939. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19940. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19941. };
  19942. /** @hidden */
  19943. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19944. if (!this.subMeshes) {
  19945. return;
  19946. }
  19947. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19948. var subMesh = _a[_i];
  19949. var material = subMesh.getMaterial();
  19950. if (material) {
  19951. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19952. }
  19953. }
  19954. };
  19955. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19956. /**
  19957. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19958. */
  19959. get: function () {
  19960. return this._scaling;
  19961. },
  19962. set: function (newScaling) {
  19963. this._scaling = newScaling;
  19964. if (this.physicsImpostor) {
  19965. this.physicsImpostor.forceUpdate();
  19966. }
  19967. },
  19968. enumerable: true,
  19969. configurable: true
  19970. });
  19971. // Methods
  19972. /**
  19973. * Disables the mesh edge rendering mode
  19974. * @returns the currentAbstractMesh
  19975. */
  19976. AbstractMesh.prototype.disableEdgesRendering = function () {
  19977. if (this._edgesRenderer) {
  19978. this._edgesRenderer.dispose();
  19979. this._edgesRenderer = null;
  19980. }
  19981. return this;
  19982. };
  19983. /**
  19984. * Enables the edge rendering mode on the mesh.
  19985. * This mode makes the mesh edges visible
  19986. * @param epsilon defines the maximal distance between two angles to detect a face
  19987. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19988. * @returns the currentAbstractMesh
  19989. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19990. */
  19991. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19992. if (epsilon === void 0) { epsilon = 0.95; }
  19993. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19994. this.disableEdgesRendering();
  19995. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19996. return this;
  19997. };
  19998. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19999. /**
  20000. * Returns true if the mesh is blocked. Implemented by child classes
  20001. */
  20002. get: function () {
  20003. return false;
  20004. },
  20005. enumerable: true,
  20006. configurable: true
  20007. });
  20008. /**
  20009. * Returns the mesh itself by default. Implemented by child classes
  20010. * @param camera defines the camera to use to pick the right LOD level
  20011. * @returns the currentAbstractMesh
  20012. */
  20013. AbstractMesh.prototype.getLOD = function (camera) {
  20014. return this;
  20015. };
  20016. /**
  20017. * Returns 0 by default. Implemented by child classes
  20018. * @returns an integer
  20019. */
  20020. AbstractMesh.prototype.getTotalVertices = function () {
  20021. return 0;
  20022. };
  20023. /**
  20024. * Returns null by default. Implemented by child classes
  20025. * @returns null
  20026. */
  20027. AbstractMesh.prototype.getIndices = function () {
  20028. return null;
  20029. };
  20030. /**
  20031. * Returns the array of the requested vertex data kind. Implemented by child classes
  20032. * @param kind defines the vertex data kind to use
  20033. * @returns null
  20034. */
  20035. AbstractMesh.prototype.getVerticesData = function (kind) {
  20036. return null;
  20037. };
  20038. /**
  20039. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20040. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20041. * Note that a new underlying VertexBuffer object is created each call.
  20042. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20043. * @param kind defines vertex data kind:
  20044. * * BABYLON.VertexBuffer.PositionKind
  20045. * * BABYLON.VertexBuffer.UVKind
  20046. * * BABYLON.VertexBuffer.UV2Kind
  20047. * * BABYLON.VertexBuffer.UV3Kind
  20048. * * BABYLON.VertexBuffer.UV4Kind
  20049. * * BABYLON.VertexBuffer.UV5Kind
  20050. * * BABYLON.VertexBuffer.UV6Kind
  20051. * * BABYLON.VertexBuffer.ColorKind
  20052. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20053. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20054. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20055. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20056. * @param data defines the data source
  20057. * @param updatable defines if the data must be flagged as updatable (or static)
  20058. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20059. * @returns the current mesh
  20060. */
  20061. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20062. return this;
  20063. };
  20064. /**
  20065. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20066. * If the mesh has no geometry, it is simply returned as it is.
  20067. * @param kind defines vertex data kind:
  20068. * * BABYLON.VertexBuffer.PositionKind
  20069. * * BABYLON.VertexBuffer.UVKind
  20070. * * BABYLON.VertexBuffer.UV2Kind
  20071. * * BABYLON.VertexBuffer.UV3Kind
  20072. * * BABYLON.VertexBuffer.UV4Kind
  20073. * * BABYLON.VertexBuffer.UV5Kind
  20074. * * BABYLON.VertexBuffer.UV6Kind
  20075. * * BABYLON.VertexBuffer.ColorKind
  20076. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20077. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20078. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20079. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20080. * @param data defines the data source
  20081. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20082. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20083. * @returns the current mesh
  20084. */
  20085. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20086. return this;
  20087. };
  20088. /**
  20089. * Sets the mesh indices,
  20090. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20091. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20092. * @param totalVertices Defines the total number of vertices
  20093. * @returns the current mesh
  20094. */
  20095. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20096. return this;
  20097. };
  20098. /**
  20099. * Gets a boolean indicating if specific vertex data is present
  20100. * @param kind defines the vertex data kind to use
  20101. * @returns true is data kind is present
  20102. */
  20103. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20104. return false;
  20105. };
  20106. /**
  20107. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20108. * @returns a BoundingInfo
  20109. */
  20110. AbstractMesh.prototype.getBoundingInfo = function () {
  20111. if (this._masterMesh) {
  20112. return this._masterMesh.getBoundingInfo();
  20113. }
  20114. if (!this._boundingInfo) {
  20115. // this._boundingInfo is being created here
  20116. this._updateBoundingInfo();
  20117. }
  20118. // cannot be null.
  20119. return this._boundingInfo;
  20120. };
  20121. /**
  20122. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20123. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20124. * @returns the current mesh
  20125. */
  20126. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20127. if (includeDescendants === void 0) { includeDescendants = true; }
  20128. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20129. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20130. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20131. if (maxDimension === 0) {
  20132. return this;
  20133. }
  20134. var scale = 1 / maxDimension;
  20135. this.scaling.scaleInPlace(scale);
  20136. return this;
  20137. };
  20138. /**
  20139. * Overwrite the current bounding info
  20140. * @param boundingInfo defines the new bounding info
  20141. * @returns the current mesh
  20142. */
  20143. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20144. this._boundingInfo = boundingInfo;
  20145. return this;
  20146. };
  20147. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20148. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20149. get: function () {
  20150. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20151. },
  20152. enumerable: true,
  20153. configurable: true
  20154. });
  20155. /** @hidden */
  20156. AbstractMesh.prototype._preActivate = function () {
  20157. };
  20158. /** @hidden */
  20159. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20160. };
  20161. /** @hidden */
  20162. AbstractMesh.prototype._activate = function (renderId) {
  20163. this._renderId = renderId;
  20164. };
  20165. /**
  20166. * Gets the current world matrix
  20167. * @returns a Matrix
  20168. */
  20169. AbstractMesh.prototype.getWorldMatrix = function () {
  20170. if (this._masterMesh) {
  20171. return this._masterMesh.getWorldMatrix();
  20172. }
  20173. return _super.prototype.getWorldMatrix.call(this);
  20174. };
  20175. /** @hidden */
  20176. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20177. if (this._masterMesh) {
  20178. return this._masterMesh._getWorldMatrixDeterminant();
  20179. }
  20180. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20181. };
  20182. // ================================== Point of View Movement =================================
  20183. /**
  20184. * Perform relative position change from the point of view of behind the front of the mesh.
  20185. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20186. * Supports definition of mesh facing forward or backward
  20187. * @param amountRight defines the distance on the right axis
  20188. * @param amountUp defines the distance on the up axis
  20189. * @param amountForward defines the distance on the forward axis
  20190. * @returns the current mesh
  20191. */
  20192. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20193. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20194. return this;
  20195. };
  20196. /**
  20197. * Calculate relative position change from the point of view of behind the front of the mesh.
  20198. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20199. * Supports definition of mesh facing forward or backward
  20200. * @param amountRight defines the distance on the right axis
  20201. * @param amountUp defines the distance on the up axis
  20202. * @param amountForward defines the distance on the forward axis
  20203. * @returns the new displacement vector
  20204. */
  20205. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20206. var rotMatrix = new BABYLON.Matrix();
  20207. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20208. rotQuaternion.toRotationMatrix(rotMatrix);
  20209. var translationDelta = BABYLON.Vector3.Zero();
  20210. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20211. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20212. return translationDelta;
  20213. };
  20214. // ================================== Point of View Rotation =================================
  20215. /**
  20216. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20217. * Supports definition of mesh facing forward or backward
  20218. * @param flipBack defines the flip
  20219. * @param twirlClockwise defines the twirl
  20220. * @param tiltRight defines the tilt
  20221. * @returns the current mesh
  20222. */
  20223. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20224. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20225. return this;
  20226. };
  20227. /**
  20228. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20229. * Supports definition of mesh facing forward or backward.
  20230. * @param flipBack defines the flip
  20231. * @param twirlClockwise defines the twirl
  20232. * @param tiltRight defines the tilt
  20233. * @returns the new rotation vector
  20234. */
  20235. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20236. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20237. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20238. };
  20239. /**
  20240. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20241. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20242. * @returns the new bounding vectors
  20243. */
  20244. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20245. if (includeDescendants === void 0) { includeDescendants = true; }
  20246. // Ensures that all world matrix will be recomputed.
  20247. this.getScene().incrementRenderId();
  20248. this.computeWorldMatrix(true);
  20249. var min;
  20250. var max;
  20251. var boundingInfo = this.getBoundingInfo();
  20252. if (!this.subMeshes) {
  20253. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20254. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20255. }
  20256. else {
  20257. min = boundingInfo.boundingBox.minimumWorld;
  20258. max = boundingInfo.boundingBox.maximumWorld;
  20259. }
  20260. if (includeDescendants) {
  20261. var descendants = this.getDescendants(false);
  20262. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20263. var descendant = descendants_1[_i];
  20264. var childMesh = descendant;
  20265. childMesh.computeWorldMatrix(true);
  20266. //make sure we have the needed params to get mix and max
  20267. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20268. continue;
  20269. }
  20270. var childBoundingInfo = childMesh.getBoundingInfo();
  20271. var boundingBox = childBoundingInfo.boundingBox;
  20272. var minBox = boundingBox.minimumWorld;
  20273. var maxBox = boundingBox.maximumWorld;
  20274. BABYLON.Tools.CheckExtends(minBox, min, max);
  20275. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20276. }
  20277. }
  20278. return {
  20279. min: min,
  20280. max: max
  20281. };
  20282. };
  20283. /** @hidden */
  20284. AbstractMesh.prototype._updateBoundingInfo = function () {
  20285. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20286. this._boundingInfo.update(this.worldMatrixFromCache);
  20287. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20288. return this;
  20289. };
  20290. /** @hidden */
  20291. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20292. if (!this.subMeshes) {
  20293. return this;
  20294. }
  20295. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20296. var subMesh = this.subMeshes[subIndex];
  20297. if (!subMesh.IsGlobal) {
  20298. subMesh.updateBoundingInfo(matrix);
  20299. }
  20300. }
  20301. return this;
  20302. };
  20303. /** @hidden */
  20304. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20305. // Bounding info
  20306. this._updateBoundingInfo();
  20307. };
  20308. /**
  20309. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20310. * A mesh is in the frustum if its bounding box intersects the frustum
  20311. * @param frustumPlanes defines the frustum to test
  20312. * @returns true if the mesh is in the frustum planes
  20313. */
  20314. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20315. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20316. };
  20317. /**
  20318. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20319. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20320. * @param frustumPlanes defines the frustum to test
  20321. * @returns true if the mesh is completely in the frustum planes
  20322. */
  20323. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20324. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20325. };
  20326. /**
  20327. * True if the mesh intersects another mesh or a SolidParticle object
  20328. * @param mesh defines a target mesh or SolidParticle to test
  20329. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20330. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20331. * @returns true if there is an intersection
  20332. */
  20333. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20334. if (precise === void 0) { precise = false; }
  20335. if (!this._boundingInfo || !mesh._boundingInfo) {
  20336. return false;
  20337. }
  20338. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20339. return true;
  20340. }
  20341. if (includeDescendants) {
  20342. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20343. var child = _a[_i];
  20344. if (child.intersectsMesh(mesh, precise, true)) {
  20345. return true;
  20346. }
  20347. }
  20348. }
  20349. return false;
  20350. };
  20351. /**
  20352. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20353. * @param point defines the point to test
  20354. * @returns true if there is an intersection
  20355. */
  20356. AbstractMesh.prototype.intersectsPoint = function (point) {
  20357. if (!this._boundingInfo) {
  20358. return false;
  20359. }
  20360. return this._boundingInfo.intersectsPoint(point);
  20361. };
  20362. /**
  20363. * Gets the current physics impostor
  20364. * @see http://doc.babylonjs.com/features/physics_engine
  20365. * @returns a physics impostor or null
  20366. */
  20367. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20368. return this.physicsImpostor;
  20369. };
  20370. /**
  20371. * Gets the position of the current mesh in camera space
  20372. * @param camera defines the camera to use
  20373. * @returns a position
  20374. */
  20375. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20376. if (camera === void 0) { camera = null; }
  20377. if (!camera) {
  20378. camera = this.getScene().activeCamera;
  20379. }
  20380. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20381. };
  20382. /**
  20383. * Returns the distance from the mesh to the active camera
  20384. * @param camera defines the camera to use
  20385. * @returns the distance
  20386. */
  20387. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20388. if (camera === void 0) { camera = null; }
  20389. if (!camera) {
  20390. camera = this.getScene().activeCamera;
  20391. }
  20392. return this.absolutePosition.subtract(camera.position).length();
  20393. };
  20394. /**
  20395. * Apply a physic impulse to the mesh
  20396. * @param force defines the force to apply
  20397. * @param contactPoint defines where to apply the force
  20398. * @returns the current mesh
  20399. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20400. */
  20401. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20402. if (!this.physicsImpostor) {
  20403. return this;
  20404. }
  20405. this.physicsImpostor.applyImpulse(force, contactPoint);
  20406. return this;
  20407. };
  20408. /**
  20409. * Creates a physic joint between two meshes
  20410. * @param otherMesh defines the other mesh to use
  20411. * @param pivot1 defines the pivot to use on this mesh
  20412. * @param pivot2 defines the pivot to use on the other mesh
  20413. * @param options defines additional options (can be plugin dependent)
  20414. * @returns the current mesh
  20415. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20416. */
  20417. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20418. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20419. return this;
  20420. }
  20421. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20422. mainPivot: pivot1,
  20423. connectedPivot: pivot2,
  20424. nativeParams: options
  20425. });
  20426. return this;
  20427. };
  20428. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20429. // Collisions
  20430. /**
  20431. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20432. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20433. */
  20434. get: function () {
  20435. return this._checkCollisions;
  20436. },
  20437. set: function (collisionEnabled) {
  20438. this._checkCollisions = collisionEnabled;
  20439. if (this.getScene().workerCollisions) {
  20440. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20441. }
  20442. },
  20443. enumerable: true,
  20444. configurable: true
  20445. });
  20446. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20447. /**
  20448. * Gets Collider object used to compute collisions (not physics)
  20449. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20450. */
  20451. get: function () {
  20452. return this._collider;
  20453. },
  20454. enumerable: true,
  20455. configurable: true
  20456. });
  20457. /**
  20458. * Move the mesh using collision engine
  20459. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20460. * @param displacement defines the requested displacement vector
  20461. * @returns the current mesh
  20462. */
  20463. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20464. var globalPosition = this.getAbsolutePosition();
  20465. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20466. if (!this._collider) {
  20467. this._collider = new BABYLON.Collider();
  20468. }
  20469. this._collider._radius = this.ellipsoid;
  20470. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20471. return this;
  20472. };
  20473. // Submeshes octree
  20474. /**
  20475. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20476. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20477. * @param maxCapacity defines the maximum size of each block (64 by default)
  20478. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20479. * @returns the new octree
  20480. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20481. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20482. */
  20483. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20484. if (maxCapacity === void 0) { maxCapacity = 64; }
  20485. if (maxDepth === void 0) { maxDepth = 2; }
  20486. if (!this._submeshesOctree) {
  20487. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20488. }
  20489. this.computeWorldMatrix(true);
  20490. var boundingInfo = this.getBoundingInfo();
  20491. // Update octree
  20492. var bbox = boundingInfo.boundingBox;
  20493. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20494. return this._submeshesOctree;
  20495. };
  20496. // Collisions
  20497. /** @hidden */
  20498. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20499. this._generatePointsArray();
  20500. if (!this._positions) {
  20501. return this;
  20502. }
  20503. // Transformation
  20504. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20505. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20506. subMesh._lastColliderWorldVertices = [];
  20507. subMesh._trianglePlanes = [];
  20508. var start = subMesh.verticesStart;
  20509. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20510. for (var i = start; i < end; i++) {
  20511. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20512. }
  20513. }
  20514. // Collide
  20515. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20516. if (collider.collisionFound) {
  20517. collider.collidedMesh = this;
  20518. }
  20519. return this;
  20520. };
  20521. /** @hidden */
  20522. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20523. var subMeshes;
  20524. var len;
  20525. // Octrees
  20526. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20527. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20528. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20529. len = intersections.length;
  20530. subMeshes = intersections.data;
  20531. }
  20532. else {
  20533. subMeshes = this.subMeshes;
  20534. len = subMeshes.length;
  20535. }
  20536. for (var index = 0; index < len; index++) {
  20537. var subMesh = subMeshes[index];
  20538. // Bounding test
  20539. if (len > 1 && !subMesh._checkCollision(collider))
  20540. continue;
  20541. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20542. }
  20543. return this;
  20544. };
  20545. /** @hidden */
  20546. AbstractMesh.prototype._checkCollision = function (collider) {
  20547. // Bounding box test
  20548. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20549. return this;
  20550. // Transformation matrix
  20551. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20552. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20553. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20554. return this;
  20555. };
  20556. // Picking
  20557. /** @hidden */
  20558. AbstractMesh.prototype._generatePointsArray = function () {
  20559. return false;
  20560. };
  20561. /**
  20562. * Checks if the passed Ray intersects with the mesh
  20563. * @param ray defines the ray to use
  20564. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20565. * @returns the picking info
  20566. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20567. */
  20568. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20569. var pickingInfo = new BABYLON.PickingInfo();
  20570. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20571. return pickingInfo;
  20572. }
  20573. if (!this._generatePointsArray()) {
  20574. return pickingInfo;
  20575. }
  20576. var intersectInfo = null;
  20577. // Octrees
  20578. var subMeshes;
  20579. var len;
  20580. if (this._submeshesOctree && this.useOctreeForPicking) {
  20581. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20582. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20583. len = intersections.length;
  20584. subMeshes = intersections.data;
  20585. }
  20586. else {
  20587. subMeshes = this.subMeshes;
  20588. len = subMeshes.length;
  20589. }
  20590. for (var index = 0; index < len; index++) {
  20591. var subMesh = subMeshes[index];
  20592. // Bounding test
  20593. if (len > 1 && !subMesh.canIntersects(ray))
  20594. continue;
  20595. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20596. if (currentIntersectInfo) {
  20597. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20598. intersectInfo = currentIntersectInfo;
  20599. intersectInfo.subMeshId = index;
  20600. if (fastCheck) {
  20601. break;
  20602. }
  20603. }
  20604. }
  20605. }
  20606. if (intersectInfo) {
  20607. // Get picked point
  20608. var world = this.getWorldMatrix();
  20609. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20610. var direction = ray.direction.clone();
  20611. direction = direction.scale(intersectInfo.distance);
  20612. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20613. var pickedPoint = worldOrigin.add(worldDirection);
  20614. // Return result
  20615. pickingInfo.hit = true;
  20616. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20617. pickingInfo.pickedPoint = pickedPoint;
  20618. pickingInfo.pickedMesh = this;
  20619. pickingInfo.bu = intersectInfo.bu || 0;
  20620. pickingInfo.bv = intersectInfo.bv || 0;
  20621. pickingInfo.faceId = intersectInfo.faceId;
  20622. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20623. return pickingInfo;
  20624. }
  20625. return pickingInfo;
  20626. };
  20627. /**
  20628. * Clones the current mesh
  20629. * @param name defines the mesh name
  20630. * @param newParent defines the new mesh parent
  20631. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20632. * @returns the new mesh
  20633. */
  20634. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20635. return null;
  20636. };
  20637. /**
  20638. * Disposes all the submeshes of the current meshnp
  20639. * @returns the current mesh
  20640. */
  20641. AbstractMesh.prototype.releaseSubMeshes = function () {
  20642. if (this.subMeshes) {
  20643. while (this.subMeshes.length) {
  20644. this.subMeshes[0].dispose();
  20645. }
  20646. }
  20647. else {
  20648. this.subMeshes = new Array();
  20649. }
  20650. return this;
  20651. };
  20652. /**
  20653. * Releases resources associated with this abstract mesh.
  20654. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20655. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20656. */
  20657. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20658. var _this = this;
  20659. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20660. var index;
  20661. // Smart Array Retainers.
  20662. this.getScene().freeActiveMeshes();
  20663. this.getScene().freeRenderingGroups();
  20664. // Action manager
  20665. if (this.actionManager !== undefined && this.actionManager !== null) {
  20666. this.actionManager.dispose();
  20667. this.actionManager = null;
  20668. }
  20669. // Skeleton
  20670. this._skeleton = null;
  20671. // Physics
  20672. if (this.physicsImpostor) {
  20673. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20674. }
  20675. // Intersections in progress
  20676. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20677. var other = this._intersectionsInProgress[index];
  20678. var pos = other._intersectionsInProgress.indexOf(this);
  20679. other._intersectionsInProgress.splice(pos, 1);
  20680. }
  20681. this._intersectionsInProgress = [];
  20682. // Lights
  20683. var lights = this.getScene().lights;
  20684. lights.forEach(function (light) {
  20685. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20686. if (meshIndex !== -1) {
  20687. light.includedOnlyMeshes.splice(meshIndex, 1);
  20688. }
  20689. meshIndex = light.excludedMeshes.indexOf(_this);
  20690. if (meshIndex !== -1) {
  20691. light.excludedMeshes.splice(meshIndex, 1);
  20692. }
  20693. // Shadow generators
  20694. var generator = light.getShadowGenerator();
  20695. if (generator) {
  20696. var shadowMap = generator.getShadowMap();
  20697. if (shadowMap && shadowMap.renderList) {
  20698. meshIndex = shadowMap.renderList.indexOf(_this);
  20699. if (meshIndex !== -1) {
  20700. shadowMap.renderList.splice(meshIndex, 1);
  20701. }
  20702. }
  20703. }
  20704. });
  20705. // Edges
  20706. if (this._edgesRenderer) {
  20707. this._edgesRenderer.dispose();
  20708. this._edgesRenderer = null;
  20709. }
  20710. // SubMeshes
  20711. if (this.getClassName() !== "InstancedMesh") {
  20712. this.releaseSubMeshes();
  20713. }
  20714. // Octree
  20715. var sceneOctree = this.getScene().selectionOctree;
  20716. if (sceneOctree !== undefined && sceneOctree !== null) {
  20717. var index = sceneOctree.dynamicContent.indexOf(this);
  20718. if (index !== -1) {
  20719. sceneOctree.dynamicContent.splice(index, 1);
  20720. }
  20721. }
  20722. // Query
  20723. var engine = this.getScene().getEngine();
  20724. if (this._occlusionQuery) {
  20725. this._isOcclusionQueryInProgress = false;
  20726. engine.deleteQuery(this._occlusionQuery);
  20727. this._occlusionQuery = null;
  20728. }
  20729. // Engine
  20730. engine.wipeCaches();
  20731. // Remove from scene
  20732. this.getScene().removeMesh(this);
  20733. if (disposeMaterialAndTextures) {
  20734. if (this.material) {
  20735. this.material.dispose(false, true);
  20736. }
  20737. }
  20738. if (!doNotRecurse) {
  20739. // Particles
  20740. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20741. if (this.getScene().particleSystems[index].emitter === this) {
  20742. this.getScene().particleSystems[index].dispose();
  20743. index--;
  20744. }
  20745. }
  20746. }
  20747. // facet data
  20748. if (this._facetDataEnabled) {
  20749. this.disableFacetData();
  20750. }
  20751. this.onAfterWorldMatrixUpdateObservable.clear();
  20752. this.onCollideObservable.clear();
  20753. this.onCollisionPositionChangeObservable.clear();
  20754. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20755. };
  20756. /**
  20757. * Adds the passed mesh as a child to the current mesh
  20758. * @param mesh defines the child mesh
  20759. * @returns the current mesh
  20760. */
  20761. AbstractMesh.prototype.addChild = function (mesh) {
  20762. mesh.setParent(this);
  20763. return this;
  20764. };
  20765. /**
  20766. * Removes the passed mesh from the current mesh children list
  20767. * @param mesh defines the child mesh
  20768. * @returns the current mesh
  20769. */
  20770. AbstractMesh.prototype.removeChild = function (mesh) {
  20771. mesh.setParent(null);
  20772. return this;
  20773. };
  20774. // Facet data
  20775. /** @hidden */
  20776. AbstractMesh.prototype._initFacetData = function () {
  20777. if (!this._facetNormals) {
  20778. this._facetNormals = new Array();
  20779. }
  20780. if (!this._facetPositions) {
  20781. this._facetPositions = new Array();
  20782. }
  20783. if (!this._facetPartitioning) {
  20784. this._facetPartitioning = new Array();
  20785. }
  20786. this._facetNb = (this.getIndices().length / 3) | 0;
  20787. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20788. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20789. for (var f = 0; f < this._facetNb; f++) {
  20790. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20791. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20792. }
  20793. this._facetDataEnabled = true;
  20794. return this;
  20795. };
  20796. /**
  20797. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20798. * This method can be called within the render loop.
  20799. * 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
  20800. * @returns the current mesh
  20801. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20802. */
  20803. AbstractMesh.prototype.updateFacetData = function () {
  20804. if (!this._facetDataEnabled) {
  20805. this._initFacetData();
  20806. }
  20807. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20808. var indices = this.getIndices();
  20809. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20810. var bInfo = this.getBoundingInfo();
  20811. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20812. // init arrays, matrix and sort function on first call
  20813. this._facetDepthSortEnabled = true;
  20814. if (indices instanceof Uint16Array) {
  20815. this._depthSortedIndices = new Uint16Array(indices);
  20816. }
  20817. else if (indices instanceof Uint32Array) {
  20818. this._depthSortedIndices = new Uint32Array(indices);
  20819. }
  20820. else {
  20821. var needs32bits = false;
  20822. for (var i = 0; i < indices.length; i++) {
  20823. if (indices[i] > 65535) {
  20824. needs32bits = true;
  20825. break;
  20826. }
  20827. }
  20828. if (needs32bits) {
  20829. this._depthSortedIndices = new Uint32Array(indices);
  20830. }
  20831. else {
  20832. this._depthSortedIndices = new Uint16Array(indices);
  20833. }
  20834. }
  20835. this._facetDepthSortFunction = function (f1, f2) {
  20836. return (f2.sqDistance - f1.sqDistance);
  20837. };
  20838. if (!this._facetDepthSortFrom) {
  20839. var camera = this.getScene().activeCamera;
  20840. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20841. }
  20842. this._depthSortedFacets = [];
  20843. for (var f = 0; f < this._facetNb; f++) {
  20844. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20845. this._depthSortedFacets.push(depthSortedFacet);
  20846. }
  20847. this._invertedMatrix = BABYLON.Matrix.Identity();
  20848. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20849. }
  20850. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20851. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20852. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20853. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20854. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20855. this._subDiv.max = this._partitioningSubdivisions;
  20856. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20857. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20858. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20859. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20860. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20861. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20862. // set the parameters for ComputeNormals()
  20863. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20864. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20865. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20866. this._facetParameters.bInfo = bInfo;
  20867. this._facetParameters.bbSize = this._bbSize;
  20868. this._facetParameters.subDiv = this._subDiv;
  20869. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20870. this._facetParameters.depthSort = this._facetDepthSort;
  20871. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20872. this.computeWorldMatrix(true);
  20873. this._worldMatrix.invertToRef(this._invertedMatrix);
  20874. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20875. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20876. }
  20877. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20878. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20879. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20880. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20881. var l = (this._depthSortedIndices.length / 3) | 0;
  20882. for (var f = 0; f < l; f++) {
  20883. var sind = this._depthSortedFacets[f].ind;
  20884. this._depthSortedIndices[f * 3] = indices[sind];
  20885. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20886. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20887. }
  20888. this.updateIndices(this._depthSortedIndices);
  20889. }
  20890. return this;
  20891. };
  20892. /**
  20893. * Returns the facetLocalNormals array.
  20894. * The normals are expressed in the mesh local spac
  20895. * @returns an array of Vector3
  20896. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20897. */
  20898. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20899. if (!this._facetNormals) {
  20900. this.updateFacetData();
  20901. }
  20902. return this._facetNormals;
  20903. };
  20904. /**
  20905. * Returns the facetLocalPositions array.
  20906. * The facet positions are expressed in the mesh local space
  20907. * @returns an array of Vector3
  20908. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20909. */
  20910. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20911. if (!this._facetPositions) {
  20912. this.updateFacetData();
  20913. }
  20914. return this._facetPositions;
  20915. };
  20916. /**
  20917. * Returns the facetLocalPartioning array
  20918. * @returns an array of array of numbers
  20919. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20920. */
  20921. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20922. if (!this._facetPartitioning) {
  20923. this.updateFacetData();
  20924. }
  20925. return this._facetPartitioning;
  20926. };
  20927. /**
  20928. * Returns the i-th facet position in the world system.
  20929. * This method allocates a new Vector3 per call
  20930. * @param i defines the facet index
  20931. * @returns a new Vector3
  20932. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20933. */
  20934. AbstractMesh.prototype.getFacetPosition = function (i) {
  20935. var pos = BABYLON.Vector3.Zero();
  20936. this.getFacetPositionToRef(i, pos);
  20937. return pos;
  20938. };
  20939. /**
  20940. * Sets the reference Vector3 with the i-th facet position in the world system
  20941. * @param i defines the facet index
  20942. * @param ref defines the target vector
  20943. * @returns the current mesh
  20944. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20945. */
  20946. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20947. var localPos = (this.getFacetLocalPositions())[i];
  20948. var world = this.getWorldMatrix();
  20949. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20950. return this;
  20951. };
  20952. /**
  20953. * Returns the i-th facet normal in the world system.
  20954. * This method allocates a new Vector3 per call
  20955. * @param i defines the facet index
  20956. * @returns a new Vector3
  20957. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20958. */
  20959. AbstractMesh.prototype.getFacetNormal = function (i) {
  20960. var norm = BABYLON.Vector3.Zero();
  20961. this.getFacetNormalToRef(i, norm);
  20962. return norm;
  20963. };
  20964. /**
  20965. * Sets the reference Vector3 with the i-th facet normal in the world system
  20966. * @param i defines the facet index
  20967. * @param ref defines the target vector
  20968. * @returns the current mesh
  20969. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20970. */
  20971. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20972. var localNorm = (this.getFacetLocalNormals())[i];
  20973. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20974. return this;
  20975. };
  20976. /**
  20977. * 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)
  20978. * @param x defines x coordinate
  20979. * @param y defines y coordinate
  20980. * @param z defines z coordinate
  20981. * @returns the array of facet indexes
  20982. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20983. */
  20984. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20985. var bInfo = this.getBoundingInfo();
  20986. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20987. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20988. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20989. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20990. return null;
  20991. }
  20992. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20993. };
  20994. /**
  20995. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20996. * @param projected sets as the (x,y,z) world projection on the facet
  20997. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  20998. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  20999. * @param x defines x coordinate
  21000. * @param y defines y coordinate
  21001. * @param z defines z coordinate
  21002. * @returns the face index if found (or null instead)
  21003. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21004. */
  21005. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21006. if (checkFace === void 0) { checkFace = false; }
  21007. if (facing === void 0) { facing = true; }
  21008. var world = this.getWorldMatrix();
  21009. var invMat = BABYLON.Tmp.Matrix[5];
  21010. world.invertToRef(invMat);
  21011. var invVect = BABYLON.Tmp.Vector3[8];
  21012. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21013. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21014. if (projected) {
  21015. // tranform the local computed projected vector to world coordinates
  21016. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21017. }
  21018. return closest;
  21019. };
  21020. /**
  21021. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21022. * @param projected sets as the (x,y,z) local projection on the facet
  21023. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21024. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21025. * @param x defines x coordinate
  21026. * @param y defines y coordinate
  21027. * @param z defines z coordinate
  21028. * @returns the face index if found (or null instead)
  21029. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21030. */
  21031. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21032. if (checkFace === void 0) { checkFace = false; }
  21033. if (facing === void 0) { facing = true; }
  21034. var closest = null;
  21035. var tmpx = 0.0;
  21036. var tmpy = 0.0;
  21037. var tmpz = 0.0;
  21038. var d = 0.0; // tmp dot facet normal * facet position
  21039. var t0 = 0.0;
  21040. var projx = 0.0;
  21041. var projy = 0.0;
  21042. var projz = 0.0;
  21043. // Get all the facets in the same partitioning block than (x, y, z)
  21044. var facetPositions = this.getFacetLocalPositions();
  21045. var facetNormals = this.getFacetLocalNormals();
  21046. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21047. if (!facetsInBlock) {
  21048. return null;
  21049. }
  21050. // Get the closest facet to (x, y, z)
  21051. var shortest = Number.MAX_VALUE; // init distance vars
  21052. var tmpDistance = shortest;
  21053. var fib; // current facet in the block
  21054. var norm; // current facet normal
  21055. var p0; // current facet barycenter position
  21056. // loop on all the facets in the current partitioning block
  21057. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21058. fib = facetsInBlock[idx];
  21059. norm = facetNormals[fib];
  21060. p0 = facetPositions[fib];
  21061. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21062. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21063. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21064. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21065. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21066. projx = x + norm.x * t0;
  21067. projy = y + norm.y * t0;
  21068. projz = z + norm.z * t0;
  21069. tmpx = projx - x;
  21070. tmpy = projy - y;
  21071. tmpz = projz - z;
  21072. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21073. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21074. shortest = tmpDistance;
  21075. closest = fib;
  21076. if (projected) {
  21077. projected.x = projx;
  21078. projected.y = projy;
  21079. projected.z = projz;
  21080. }
  21081. }
  21082. }
  21083. }
  21084. return closest;
  21085. };
  21086. /**
  21087. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21088. * @returns the parameters
  21089. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21090. */
  21091. AbstractMesh.prototype.getFacetDataParameters = function () {
  21092. return this._facetParameters;
  21093. };
  21094. /**
  21095. * Disables the feature FacetData and frees the related memory
  21096. * @returns the current mesh
  21097. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21098. */
  21099. AbstractMesh.prototype.disableFacetData = function () {
  21100. if (this._facetDataEnabled) {
  21101. this._facetDataEnabled = false;
  21102. this._facetPositions = new Array();
  21103. this._facetNormals = new Array();
  21104. this._facetPartitioning = new Array();
  21105. this._facetParameters = null;
  21106. this._depthSortedIndices = new Uint32Array(0);
  21107. }
  21108. return this;
  21109. };
  21110. /**
  21111. * Updates the AbstractMesh indices array
  21112. * @param indices defines the data source
  21113. * @returns the current mesh
  21114. */
  21115. AbstractMesh.prototype.updateIndices = function (indices) {
  21116. return this;
  21117. };
  21118. /**
  21119. * Creates new normals data for the mesh
  21120. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21121. * @returns the current mesh
  21122. */
  21123. AbstractMesh.prototype.createNormals = function (updatable) {
  21124. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21125. var indices = this.getIndices();
  21126. var normals;
  21127. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21128. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21129. }
  21130. else {
  21131. normals = [];
  21132. }
  21133. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21134. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21135. return this;
  21136. };
  21137. /**
  21138. * Align the mesh with a normal
  21139. * @param normal defines the normal to use
  21140. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21141. * @returns the current mesh
  21142. */
  21143. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21144. if (!upDirection) {
  21145. upDirection = BABYLON.Axis.Y;
  21146. }
  21147. var axisX = BABYLON.Tmp.Vector3[0];
  21148. var axisZ = BABYLON.Tmp.Vector3[1];
  21149. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21150. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21151. if (this.rotationQuaternion) {
  21152. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21153. }
  21154. else {
  21155. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21156. }
  21157. return this;
  21158. };
  21159. /** @hidden */
  21160. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21161. var engine = this.getEngine();
  21162. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21163. this._isOccluded = false;
  21164. return;
  21165. }
  21166. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21167. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21168. if (isOcclusionQueryAvailable) {
  21169. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21170. this._isOcclusionQueryInProgress = false;
  21171. this._occlusionInternalRetryCounter = 0;
  21172. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21173. }
  21174. else {
  21175. this._occlusionInternalRetryCounter++;
  21176. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21177. this._isOcclusionQueryInProgress = false;
  21178. this._occlusionInternalRetryCounter = 0;
  21179. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21180. // if strict continue the last state of the object.
  21181. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21182. }
  21183. else {
  21184. return;
  21185. }
  21186. }
  21187. }
  21188. var scene = this.getScene();
  21189. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21190. if (!this._occlusionQuery) {
  21191. this._occlusionQuery = engine.createQuery();
  21192. }
  21193. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21194. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21195. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21196. this._isOcclusionQueryInProgress = true;
  21197. };
  21198. /** No occlusion */
  21199. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21200. /** Occlusion set to optimisitic */
  21201. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21202. /** Occlusion set to strict */
  21203. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21204. /** Use an accurante occlusion algorithm */
  21205. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21206. /** Use a conservative occlusion algorithm */
  21207. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21208. return AbstractMesh;
  21209. }(BABYLON.TransformNode));
  21210. BABYLON.AbstractMesh = AbstractMesh;
  21211. })(BABYLON || (BABYLON = {}));
  21212. //# sourceMappingURL=babylon.abstractMesh.js.map
  21213. var BABYLON;
  21214. (function (BABYLON) {
  21215. /**
  21216. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21217. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21218. * 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.
  21219. */
  21220. var Light = /** @class */ (function (_super) {
  21221. __extends(Light, _super);
  21222. /**
  21223. * Creates a Light object in the scene.
  21224. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21225. * @param name The firendly name of the light
  21226. * @param scene The scene the light belongs too
  21227. */
  21228. function Light(name, scene) {
  21229. var _this = _super.call(this, name, scene) || this;
  21230. /**
  21231. * Diffuse gives the basic color to an object.
  21232. */
  21233. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21234. /**
  21235. * Specular produces a highlight color on an object.
  21236. * Note: This is note affecting PBR materials.
  21237. */
  21238. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21239. /**
  21240. * Strength of the light.
  21241. * Note: By default it is define in the framework own unit.
  21242. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21243. */
  21244. _this.intensity = 1.0;
  21245. /**
  21246. * Defines how far from the source the light is impacting in scene units.
  21247. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21248. */
  21249. _this.range = Number.MAX_VALUE;
  21250. /**
  21251. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21252. * of light.
  21253. */
  21254. _this._photometricScale = 1.0;
  21255. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21256. _this._radius = 0.00001;
  21257. /**
  21258. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21259. * exceeding the number allowed of the materials.
  21260. */
  21261. _this.renderPriority = 0;
  21262. /**
  21263. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21264. * the current shadow generator.
  21265. */
  21266. _this.shadowEnabled = true;
  21267. _this._excludeWithLayerMask = 0;
  21268. _this._includeOnlyWithLayerMask = 0;
  21269. _this._lightmapMode = 0;
  21270. /**
  21271. * @hidden Internal use only.
  21272. */
  21273. _this._excludedMeshesIds = new Array();
  21274. /**
  21275. * @hidden Internal use only.
  21276. */
  21277. _this._includedOnlyMeshesIds = new Array();
  21278. _this.getScene().addLight(_this);
  21279. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21280. _this._buildUniformLayout();
  21281. _this.includedOnlyMeshes = new Array();
  21282. _this.excludedMeshes = new Array();
  21283. _this._resyncMeshes();
  21284. return _this;
  21285. }
  21286. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21287. /**
  21288. * If every light affecting the material is in this lightmapMode,
  21289. * material.lightmapTexture adds or multiplies
  21290. * (depends on material.useLightmapAsShadowmap)
  21291. * after every other light calculations.
  21292. */
  21293. get: function () {
  21294. return Light._LIGHTMAP_DEFAULT;
  21295. },
  21296. enumerable: true,
  21297. configurable: true
  21298. });
  21299. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21300. /**
  21301. * material.lightmapTexture as only diffuse lighting from this light
  21302. * adds only specular lighting from this light
  21303. * adds dynamic shadows
  21304. */
  21305. get: function () {
  21306. return Light._LIGHTMAP_SPECULAR;
  21307. },
  21308. enumerable: true,
  21309. configurable: true
  21310. });
  21311. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21312. /**
  21313. * material.lightmapTexture as only lighting
  21314. * no light calculation from this light
  21315. * only adds dynamic shadows from this light
  21316. */
  21317. get: function () {
  21318. return Light._LIGHTMAP_SHADOWSONLY;
  21319. },
  21320. enumerable: true,
  21321. configurable: true
  21322. });
  21323. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21324. /**
  21325. * Each light type uses the default quantity according to its type:
  21326. * point/spot lights use luminous intensity
  21327. * directional lights use illuminance
  21328. */
  21329. get: function () {
  21330. return Light._INTENSITYMODE_AUTOMATIC;
  21331. },
  21332. enumerable: true,
  21333. configurable: true
  21334. });
  21335. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21336. /**
  21337. * lumen (lm)
  21338. */
  21339. get: function () {
  21340. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21341. },
  21342. enumerable: true,
  21343. configurable: true
  21344. });
  21345. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21346. /**
  21347. * candela (lm/sr)
  21348. */
  21349. get: function () {
  21350. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21351. },
  21352. enumerable: true,
  21353. configurable: true
  21354. });
  21355. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21356. /**
  21357. * lux (lm/m^2)
  21358. */
  21359. get: function () {
  21360. return Light._INTENSITYMODE_ILLUMINANCE;
  21361. },
  21362. enumerable: true,
  21363. configurable: true
  21364. });
  21365. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21366. /**
  21367. * nit (cd/m^2)
  21368. */
  21369. get: function () {
  21370. return Light._INTENSITYMODE_LUMINANCE;
  21371. },
  21372. enumerable: true,
  21373. configurable: true
  21374. });
  21375. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21376. /**
  21377. * Light type const id of the point light.
  21378. */
  21379. get: function () {
  21380. return Light._LIGHTTYPEID_POINTLIGHT;
  21381. },
  21382. enumerable: true,
  21383. configurable: true
  21384. });
  21385. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21386. /**
  21387. * Light type const id of the directional light.
  21388. */
  21389. get: function () {
  21390. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21391. },
  21392. enumerable: true,
  21393. configurable: true
  21394. });
  21395. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21396. /**
  21397. * Light type const id of the spot light.
  21398. */
  21399. get: function () {
  21400. return Light._LIGHTTYPEID_SPOTLIGHT;
  21401. },
  21402. enumerable: true,
  21403. configurable: true
  21404. });
  21405. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21406. /**
  21407. * Light type const id of the hemispheric light.
  21408. */
  21409. get: function () {
  21410. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21411. },
  21412. enumerable: true,
  21413. configurable: true
  21414. });
  21415. Object.defineProperty(Light.prototype, "intensityMode", {
  21416. /**
  21417. * Gets the photometric scale used to interpret the intensity.
  21418. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21419. */
  21420. get: function () {
  21421. return this._intensityMode;
  21422. },
  21423. /**
  21424. * Sets the photometric scale used to interpret the intensity.
  21425. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21426. */
  21427. set: function (value) {
  21428. this._intensityMode = value;
  21429. this._computePhotometricScale();
  21430. },
  21431. enumerable: true,
  21432. configurable: true
  21433. });
  21434. ;
  21435. ;
  21436. Object.defineProperty(Light.prototype, "radius", {
  21437. /**
  21438. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21439. */
  21440. get: function () {
  21441. return this._radius;
  21442. },
  21443. /**
  21444. * sets the light radius used by PBR Materials to simulate soft area lights.
  21445. */
  21446. set: function (value) {
  21447. this._radius = value;
  21448. this._computePhotometricScale();
  21449. },
  21450. enumerable: true,
  21451. configurable: true
  21452. });
  21453. ;
  21454. ;
  21455. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21456. /**
  21457. * Gets the only meshes impacted by this light.
  21458. */
  21459. get: function () {
  21460. return this._includedOnlyMeshes;
  21461. },
  21462. /**
  21463. * Sets the only meshes impacted by this light.
  21464. */
  21465. set: function (value) {
  21466. this._includedOnlyMeshes = value;
  21467. this._hookArrayForIncludedOnly(value);
  21468. },
  21469. enumerable: true,
  21470. configurable: true
  21471. });
  21472. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21473. /**
  21474. * Gets the meshes not impacted by this light.
  21475. */
  21476. get: function () {
  21477. return this._excludedMeshes;
  21478. },
  21479. /**
  21480. * Sets the meshes not impacted by this light.
  21481. */
  21482. set: function (value) {
  21483. this._excludedMeshes = value;
  21484. this._hookArrayForExcluded(value);
  21485. },
  21486. enumerable: true,
  21487. configurable: true
  21488. });
  21489. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21490. /**
  21491. * Gets the layer id use to find what meshes are not impacted by the light.
  21492. * Inactive if 0
  21493. */
  21494. get: function () {
  21495. return this._excludeWithLayerMask;
  21496. },
  21497. /**
  21498. * Sets the layer id use to find what meshes are not impacted by the light.
  21499. * Inactive if 0
  21500. */
  21501. set: function (value) {
  21502. this._excludeWithLayerMask = value;
  21503. this._resyncMeshes();
  21504. },
  21505. enumerable: true,
  21506. configurable: true
  21507. });
  21508. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21509. /**
  21510. * Gets the layer id use to find what meshes are impacted by the light.
  21511. * Inactive if 0
  21512. */
  21513. get: function () {
  21514. return this._includeOnlyWithLayerMask;
  21515. },
  21516. /**
  21517. * Sets the layer id use to find what meshes are impacted by the light.
  21518. * Inactive if 0
  21519. */
  21520. set: function (value) {
  21521. this._includeOnlyWithLayerMask = value;
  21522. this._resyncMeshes();
  21523. },
  21524. enumerable: true,
  21525. configurable: true
  21526. });
  21527. Object.defineProperty(Light.prototype, "lightmapMode", {
  21528. /**
  21529. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21530. */
  21531. get: function () {
  21532. return this._lightmapMode;
  21533. },
  21534. /**
  21535. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21536. */
  21537. set: function (value) {
  21538. if (this._lightmapMode === value) {
  21539. return;
  21540. }
  21541. this._lightmapMode = value;
  21542. this._markMeshesAsLightDirty();
  21543. },
  21544. enumerable: true,
  21545. configurable: true
  21546. });
  21547. /**
  21548. * Returns the string "Light".
  21549. * @returns the class name
  21550. */
  21551. Light.prototype.getClassName = function () {
  21552. return "Light";
  21553. };
  21554. /**
  21555. * Converts the light information to a readable string for debug purpose.
  21556. * @param fullDetails Supports for multiple levels of logging within scene loading
  21557. * @returns the human readable light info
  21558. */
  21559. Light.prototype.toString = function (fullDetails) {
  21560. var ret = "Name: " + this.name;
  21561. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21562. if (this.animations) {
  21563. for (var i = 0; i < this.animations.length; i++) {
  21564. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21565. }
  21566. }
  21567. if (fullDetails) {
  21568. }
  21569. return ret;
  21570. };
  21571. /**
  21572. * Set the enabled state of this node.
  21573. * @param value - the new enabled state
  21574. */
  21575. Light.prototype.setEnabled = function (value) {
  21576. _super.prototype.setEnabled.call(this, value);
  21577. this._resyncMeshes();
  21578. };
  21579. /**
  21580. * Returns the Light associated shadow generator if any.
  21581. * @return the associated shadow generator.
  21582. */
  21583. Light.prototype.getShadowGenerator = function () {
  21584. return this._shadowGenerator;
  21585. };
  21586. /**
  21587. * Returns a Vector3, the absolute light position in the World.
  21588. * @returns the world space position of the light
  21589. */
  21590. Light.prototype.getAbsolutePosition = function () {
  21591. return BABYLON.Vector3.Zero();
  21592. };
  21593. /**
  21594. * Specifies if the light will affect the passed mesh.
  21595. * @param mesh The mesh to test against the light
  21596. * @return true the mesh is affected otherwise, false.
  21597. */
  21598. Light.prototype.canAffectMesh = function (mesh) {
  21599. if (!mesh) {
  21600. return true;
  21601. }
  21602. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21603. return false;
  21604. }
  21605. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21606. return false;
  21607. }
  21608. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21609. return false;
  21610. }
  21611. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21612. return false;
  21613. }
  21614. return true;
  21615. };
  21616. /**
  21617. * Computes and Returns the light World matrix.
  21618. * @returns the world matrix
  21619. */
  21620. Light.prototype.getWorldMatrix = function () {
  21621. this._currentRenderId = this.getScene().getRenderId();
  21622. this._childRenderId = this._currentRenderId;
  21623. var worldMatrix = this._getWorldMatrix();
  21624. if (this.parent && this.parent.getWorldMatrix) {
  21625. if (!this._parentedWorldMatrix) {
  21626. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21627. }
  21628. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21629. this._markSyncedWithParent();
  21630. return this._parentedWorldMatrix;
  21631. }
  21632. return worldMatrix;
  21633. };
  21634. /**
  21635. * Sort function to order lights for rendering.
  21636. * @param a First Light object to compare to second.
  21637. * @param b Second Light object to compare first.
  21638. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21639. */
  21640. Light.CompareLightsPriority = function (a, b) {
  21641. //shadow-casting lights have priority over non-shadow-casting lights
  21642. //the renderPrioirty is a secondary sort criterion
  21643. if (a.shadowEnabled !== b.shadowEnabled) {
  21644. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21645. }
  21646. return b.renderPriority - a.renderPriority;
  21647. };
  21648. /**
  21649. * Releases resources associated with this node.
  21650. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21651. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21652. */
  21653. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21654. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21655. if (this._shadowGenerator) {
  21656. this._shadowGenerator.dispose();
  21657. this._shadowGenerator = null;
  21658. }
  21659. // Animations
  21660. this.getScene().stopAnimation(this);
  21661. // Remove from meshes
  21662. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21663. var mesh = _a[_i];
  21664. mesh._removeLightSource(this);
  21665. }
  21666. this._uniformBuffer.dispose();
  21667. // Remove from scene
  21668. this.getScene().removeLight(this);
  21669. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21670. };
  21671. /**
  21672. * Returns the light type ID (integer).
  21673. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21674. */
  21675. Light.prototype.getTypeID = function () {
  21676. return 0;
  21677. };
  21678. /**
  21679. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21680. * @returns the scaled intensity in intensity mode unit
  21681. */
  21682. Light.prototype.getScaledIntensity = function () {
  21683. return this._photometricScale * this.intensity;
  21684. };
  21685. /**
  21686. * Returns a new Light object, named "name", from the current one.
  21687. * @param name The name of the cloned light
  21688. * @returns the new created light
  21689. */
  21690. Light.prototype.clone = function (name) {
  21691. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21692. if (!constructor) {
  21693. return null;
  21694. }
  21695. return BABYLON.SerializationHelper.Clone(constructor, this);
  21696. };
  21697. /**
  21698. * Serializes the current light into a Serialization object.
  21699. * @returns the serialized object.
  21700. */
  21701. Light.prototype.serialize = function () {
  21702. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21703. // Type
  21704. serializationObject.type = this.getTypeID();
  21705. // Parent
  21706. if (this.parent) {
  21707. serializationObject.parentId = this.parent.id;
  21708. }
  21709. // Inclusion / exclusions
  21710. if (this.excludedMeshes.length > 0) {
  21711. serializationObject.excludedMeshesIds = [];
  21712. this.excludedMeshes.forEach(function (mesh) {
  21713. serializationObject.excludedMeshesIds.push(mesh.id);
  21714. });
  21715. }
  21716. if (this.includedOnlyMeshes.length > 0) {
  21717. serializationObject.includedOnlyMeshesIds = [];
  21718. this.includedOnlyMeshes.forEach(function (mesh) {
  21719. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21720. });
  21721. }
  21722. // Animations
  21723. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21724. serializationObject.ranges = this.serializeAnimationRanges();
  21725. return serializationObject;
  21726. };
  21727. /**
  21728. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21729. * This new light is named "name" and added to the passed scene.
  21730. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21731. * @param name The friendly name of the light
  21732. * @param scene The scene the new light will belong to
  21733. * @returns the constructor function
  21734. */
  21735. Light.GetConstructorFromName = function (type, name, scene) {
  21736. switch (type) {
  21737. case 0:
  21738. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21739. case 1:
  21740. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21741. case 2:
  21742. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21743. case 3:
  21744. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21745. }
  21746. return null;
  21747. };
  21748. /**
  21749. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21750. * @param parsedLight The JSON representation of the light
  21751. * @param scene The scene to create the parsed light in
  21752. * @returns the created light after parsing
  21753. */
  21754. Light.Parse = function (parsedLight, scene) {
  21755. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21756. if (!constructor) {
  21757. return null;
  21758. }
  21759. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21760. // Inclusion / exclusions
  21761. if (parsedLight.excludedMeshesIds) {
  21762. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21763. }
  21764. if (parsedLight.includedOnlyMeshesIds) {
  21765. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21766. }
  21767. // Parent
  21768. if (parsedLight.parentId) {
  21769. light._waitingParentId = parsedLight.parentId;
  21770. }
  21771. // Animations
  21772. if (parsedLight.animations) {
  21773. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21774. var parsedAnimation = parsedLight.animations[animationIndex];
  21775. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21776. }
  21777. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21778. }
  21779. if (parsedLight.autoAnimate) {
  21780. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21781. }
  21782. return light;
  21783. };
  21784. Light.prototype._hookArrayForExcluded = function (array) {
  21785. var _this = this;
  21786. var oldPush = array.push;
  21787. array.push = function () {
  21788. var items = [];
  21789. for (var _i = 0; _i < arguments.length; _i++) {
  21790. items[_i] = arguments[_i];
  21791. }
  21792. var result = oldPush.apply(array, items);
  21793. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21794. var item = items_1[_a];
  21795. item._resyncLighSource(_this);
  21796. }
  21797. return result;
  21798. };
  21799. var oldSplice = array.splice;
  21800. array.splice = function (index, deleteCount) {
  21801. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21802. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21803. var item = deleted_1[_i];
  21804. item._resyncLighSource(_this);
  21805. }
  21806. return deleted;
  21807. };
  21808. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21809. var item = array_1[_i];
  21810. item._resyncLighSource(this);
  21811. }
  21812. };
  21813. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21814. var _this = this;
  21815. var oldPush = array.push;
  21816. array.push = function () {
  21817. var items = [];
  21818. for (var _i = 0; _i < arguments.length; _i++) {
  21819. items[_i] = arguments[_i];
  21820. }
  21821. var result = oldPush.apply(array, items);
  21822. _this._resyncMeshes();
  21823. return result;
  21824. };
  21825. var oldSplice = array.splice;
  21826. array.splice = function (index, deleteCount) {
  21827. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21828. _this._resyncMeshes();
  21829. return deleted;
  21830. };
  21831. this._resyncMeshes();
  21832. };
  21833. Light.prototype._resyncMeshes = function () {
  21834. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21835. var mesh = _a[_i];
  21836. mesh._resyncLighSource(this);
  21837. }
  21838. };
  21839. /**
  21840. * Forces the meshes to update their light related information in their rendering used effects
  21841. * @hidden Internal Use Only
  21842. */
  21843. Light.prototype._markMeshesAsLightDirty = function () {
  21844. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21845. var mesh = _a[_i];
  21846. if (mesh._lightSources.indexOf(this) !== -1) {
  21847. mesh._markSubMeshesAsLightDirty();
  21848. }
  21849. }
  21850. };
  21851. /**
  21852. * Recomputes the cached photometric scale if needed.
  21853. */
  21854. Light.prototype._computePhotometricScale = function () {
  21855. this._photometricScale = this._getPhotometricScale();
  21856. this.getScene().resetCachedMaterial();
  21857. };
  21858. /**
  21859. * Returns the Photometric Scale according to the light type and intensity mode.
  21860. */
  21861. Light.prototype._getPhotometricScale = function () {
  21862. var photometricScale = 0.0;
  21863. var lightTypeID = this.getTypeID();
  21864. //get photometric mode
  21865. var photometricMode = this.intensityMode;
  21866. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21867. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21868. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21869. }
  21870. else {
  21871. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21872. }
  21873. }
  21874. //compute photometric scale
  21875. switch (lightTypeID) {
  21876. case Light.LIGHTTYPEID_POINTLIGHT:
  21877. case Light.LIGHTTYPEID_SPOTLIGHT:
  21878. switch (photometricMode) {
  21879. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21880. photometricScale = 1.0 / (4.0 * Math.PI);
  21881. break;
  21882. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21883. photometricScale = 1.0;
  21884. break;
  21885. case Light.INTENSITYMODE_LUMINANCE:
  21886. photometricScale = this.radius * this.radius;
  21887. break;
  21888. }
  21889. break;
  21890. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21891. switch (photometricMode) {
  21892. case Light.INTENSITYMODE_ILLUMINANCE:
  21893. photometricScale = 1.0;
  21894. break;
  21895. case Light.INTENSITYMODE_LUMINANCE:
  21896. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21897. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21898. var apexAngleRadians = this.radius;
  21899. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21900. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21901. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21902. photometricScale = solidAngle;
  21903. break;
  21904. }
  21905. break;
  21906. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21907. // No fall off in hemisperic light.
  21908. photometricScale = 1.0;
  21909. break;
  21910. }
  21911. return photometricScale;
  21912. };
  21913. /**
  21914. * Reorder the light in the scene according to their defined priority.
  21915. * @hidden Internal Use Only
  21916. */
  21917. Light.prototype._reorderLightsInScene = function () {
  21918. var scene = this.getScene();
  21919. if (this._renderPriority != 0) {
  21920. scene.requireLightSorting = true;
  21921. }
  21922. this.getScene().sortLightsByPriority();
  21923. };
  21924. //lightmapMode Consts
  21925. Light._LIGHTMAP_DEFAULT = 0;
  21926. Light._LIGHTMAP_SPECULAR = 1;
  21927. Light._LIGHTMAP_SHADOWSONLY = 2;
  21928. // Intensity Mode Consts
  21929. Light._INTENSITYMODE_AUTOMATIC = 0;
  21930. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21931. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21932. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21933. Light._INTENSITYMODE_LUMINANCE = 4;
  21934. // Light types ids const.
  21935. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21936. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21937. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21938. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21939. __decorate([
  21940. BABYLON.serializeAsColor3()
  21941. ], Light.prototype, "diffuse", void 0);
  21942. __decorate([
  21943. BABYLON.serializeAsColor3()
  21944. ], Light.prototype, "specular", void 0);
  21945. __decorate([
  21946. BABYLON.serialize()
  21947. ], Light.prototype, "intensity", void 0);
  21948. __decorate([
  21949. BABYLON.serialize()
  21950. ], Light.prototype, "range", void 0);
  21951. __decorate([
  21952. BABYLON.serialize()
  21953. ], Light.prototype, "intensityMode", null);
  21954. __decorate([
  21955. BABYLON.serialize()
  21956. ], Light.prototype, "radius", null);
  21957. __decorate([
  21958. BABYLON.serialize()
  21959. ], Light.prototype, "_renderPriority", void 0);
  21960. __decorate([
  21961. BABYLON.expandToProperty("_reorderLightsInScene")
  21962. ], Light.prototype, "renderPriority", void 0);
  21963. __decorate([
  21964. BABYLON.serialize()
  21965. ], Light.prototype, "shadowEnabled", void 0);
  21966. __decorate([
  21967. BABYLON.serialize("excludeWithLayerMask")
  21968. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21969. __decorate([
  21970. BABYLON.serialize("includeOnlyWithLayerMask")
  21971. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21972. __decorate([
  21973. BABYLON.serialize("lightmapMode")
  21974. ], Light.prototype, "_lightmapMode", void 0);
  21975. return Light;
  21976. }(BABYLON.Node));
  21977. BABYLON.Light = Light;
  21978. })(BABYLON || (BABYLON = {}));
  21979. //# sourceMappingURL=babylon.light.js.map
  21980. var BABYLON;
  21981. (function (BABYLON) {
  21982. var Camera = /** @class */ (function (_super) {
  21983. __extends(Camera, _super);
  21984. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21985. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21986. var _this = _super.call(this, name, scene) || this;
  21987. /**
  21988. * The vector the camera should consider as up.
  21989. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21990. */
  21991. _this.upVector = BABYLON.Vector3.Up();
  21992. _this.orthoLeft = null;
  21993. _this.orthoRight = null;
  21994. _this.orthoBottom = null;
  21995. _this.orthoTop = null;
  21996. /**
  21997. * FOV is set in Radians. (default is 0.8)
  21998. */
  21999. _this.fov = 0.8;
  22000. _this.minZ = 1;
  22001. _this.maxZ = 10000.0;
  22002. _this.inertia = 0.9;
  22003. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22004. _this.isIntermediate = false;
  22005. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22006. /**
  22007. * Restricts the camera to viewing objects with the same layerMask.
  22008. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22009. */
  22010. _this.layerMask = 0x0FFFFFFF;
  22011. /**
  22012. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22013. */
  22014. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22015. // Camera rig members
  22016. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22017. _this._rigCameras = new Array();
  22018. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22019. _this._skipRendering = false;
  22020. _this.customRenderTargets = new Array();
  22021. // Observables
  22022. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22023. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22024. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22025. _this.onRestoreStateObservable = new BABYLON.Observable();
  22026. // Cache
  22027. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22028. _this._projectionMatrix = new BABYLON.Matrix();
  22029. _this._doNotComputeProjectionMatrix = false;
  22030. _this._worldMatrix = BABYLON.Matrix.Identity();
  22031. _this._postProcesses = new Array();
  22032. _this._transformMatrix = BABYLON.Matrix.Zero();
  22033. _this._activeMeshes = new BABYLON.SmartArray(256);
  22034. _this._globalPosition = BABYLON.Vector3.Zero();
  22035. _this._refreshFrustumPlanes = true;
  22036. _this.getScene().addCamera(_this);
  22037. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22038. _this.getScene().activeCamera = _this;
  22039. }
  22040. _this.position = position;
  22041. return _this;
  22042. }
  22043. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22044. get: function () {
  22045. return Camera._PERSPECTIVE_CAMERA;
  22046. },
  22047. enumerable: true,
  22048. configurable: true
  22049. });
  22050. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22051. get: function () {
  22052. return Camera._ORTHOGRAPHIC_CAMERA;
  22053. },
  22054. enumerable: true,
  22055. configurable: true
  22056. });
  22057. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22058. /**
  22059. * This is the default FOV mode for perspective cameras.
  22060. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22061. *
  22062. */
  22063. get: function () {
  22064. return Camera._FOVMODE_VERTICAL_FIXED;
  22065. },
  22066. enumerable: true,
  22067. configurable: true
  22068. });
  22069. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22070. /**
  22071. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22072. *
  22073. */
  22074. get: function () {
  22075. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22076. },
  22077. enumerable: true,
  22078. configurable: true
  22079. });
  22080. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22081. get: function () {
  22082. return Camera._RIG_MODE_NONE;
  22083. },
  22084. enumerable: true,
  22085. configurable: true
  22086. });
  22087. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22088. get: function () {
  22089. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22090. },
  22091. enumerable: true,
  22092. configurable: true
  22093. });
  22094. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22095. get: function () {
  22096. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22097. },
  22098. enumerable: true,
  22099. configurable: true
  22100. });
  22101. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22102. get: function () {
  22103. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22104. },
  22105. enumerable: true,
  22106. configurable: true
  22107. });
  22108. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22109. get: function () {
  22110. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22111. },
  22112. enumerable: true,
  22113. configurable: true
  22114. });
  22115. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22116. get: function () {
  22117. return Camera._RIG_MODE_VR;
  22118. },
  22119. enumerable: true,
  22120. configurable: true
  22121. });
  22122. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22123. get: function () {
  22124. return Camera._RIG_MODE_WEBVR;
  22125. },
  22126. enumerable: true,
  22127. configurable: true
  22128. });
  22129. /**
  22130. * Store current camera state (fov, position, etc..)
  22131. */
  22132. Camera.prototype.storeState = function () {
  22133. this._stateStored = true;
  22134. this._storedFov = this.fov;
  22135. return this;
  22136. };
  22137. /**
  22138. * Restores the camera state values if it has been stored. You must call storeState() first
  22139. */
  22140. Camera.prototype._restoreStateValues = function () {
  22141. if (!this._stateStored) {
  22142. return false;
  22143. }
  22144. this.fov = this._storedFov;
  22145. return true;
  22146. };
  22147. /**
  22148. * Restored camera state. You must call storeState() first
  22149. */
  22150. Camera.prototype.restoreState = function () {
  22151. if (this._restoreStateValues()) {
  22152. this.onRestoreStateObservable.notifyObservers(this);
  22153. return true;
  22154. }
  22155. return false;
  22156. };
  22157. Camera.prototype.getClassName = function () {
  22158. return "Camera";
  22159. };
  22160. /**
  22161. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22162. */
  22163. Camera.prototype.toString = function (fullDetails) {
  22164. var ret = "Name: " + this.name;
  22165. ret += ", type: " + this.getClassName();
  22166. if (this.animations) {
  22167. for (var i = 0; i < this.animations.length; i++) {
  22168. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22169. }
  22170. }
  22171. if (fullDetails) {
  22172. }
  22173. return ret;
  22174. };
  22175. Object.defineProperty(Camera.prototype, "globalPosition", {
  22176. get: function () {
  22177. return this._globalPosition;
  22178. },
  22179. enumerable: true,
  22180. configurable: true
  22181. });
  22182. Camera.prototype.getActiveMeshes = function () {
  22183. return this._activeMeshes;
  22184. };
  22185. Camera.prototype.isActiveMesh = function (mesh) {
  22186. return (this._activeMeshes.indexOf(mesh) !== -1);
  22187. };
  22188. /**
  22189. * Is this camera ready to be used/rendered
  22190. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22191. * @return true if the camera is ready
  22192. */
  22193. Camera.prototype.isReady = function (completeCheck) {
  22194. if (completeCheck === void 0) { completeCheck = false; }
  22195. if (completeCheck) {
  22196. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22197. var pp = _a[_i];
  22198. if (pp && !pp.isReady()) {
  22199. return false;
  22200. }
  22201. }
  22202. }
  22203. return _super.prototype.isReady.call(this, completeCheck);
  22204. };
  22205. //Cache
  22206. Camera.prototype._initCache = function () {
  22207. _super.prototype._initCache.call(this);
  22208. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22209. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22210. this._cache.mode = undefined;
  22211. this._cache.minZ = undefined;
  22212. this._cache.maxZ = undefined;
  22213. this._cache.fov = undefined;
  22214. this._cache.fovMode = undefined;
  22215. this._cache.aspectRatio = undefined;
  22216. this._cache.orthoLeft = undefined;
  22217. this._cache.orthoRight = undefined;
  22218. this._cache.orthoBottom = undefined;
  22219. this._cache.orthoTop = undefined;
  22220. this._cache.renderWidth = undefined;
  22221. this._cache.renderHeight = undefined;
  22222. };
  22223. Camera.prototype._updateCache = function (ignoreParentClass) {
  22224. if (!ignoreParentClass) {
  22225. _super.prototype._updateCache.call(this);
  22226. }
  22227. this._cache.position.copyFrom(this.position);
  22228. this._cache.upVector.copyFrom(this.upVector);
  22229. };
  22230. // Synchronized
  22231. Camera.prototype._isSynchronized = function () {
  22232. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22233. };
  22234. Camera.prototype._isSynchronizedViewMatrix = function () {
  22235. if (!_super.prototype._isSynchronized.call(this))
  22236. return false;
  22237. return this._cache.position.equals(this.position)
  22238. && this._cache.upVector.equals(this.upVector)
  22239. && this.isSynchronizedWithParent();
  22240. };
  22241. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22242. var check = this._cache.mode === this.mode
  22243. && this._cache.minZ === this.minZ
  22244. && this._cache.maxZ === this.maxZ;
  22245. if (!check) {
  22246. return false;
  22247. }
  22248. var engine = this.getEngine();
  22249. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22250. check = this._cache.fov === this.fov
  22251. && this._cache.fovMode === this.fovMode
  22252. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22253. }
  22254. else {
  22255. check = this._cache.orthoLeft === this.orthoLeft
  22256. && this._cache.orthoRight === this.orthoRight
  22257. && this._cache.orthoBottom === this.orthoBottom
  22258. && this._cache.orthoTop === this.orthoTop
  22259. && this._cache.renderWidth === engine.getRenderWidth()
  22260. && this._cache.renderHeight === engine.getRenderHeight();
  22261. }
  22262. return check;
  22263. };
  22264. // Controls
  22265. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22266. };
  22267. Camera.prototype.detachControl = function (element) {
  22268. };
  22269. Camera.prototype.update = function () {
  22270. this._checkInputs();
  22271. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22272. this._updateRigCameras();
  22273. }
  22274. };
  22275. Camera.prototype._checkInputs = function () {
  22276. this.onAfterCheckInputsObservable.notifyObservers(this);
  22277. };
  22278. Object.defineProperty(Camera.prototype, "rigCameras", {
  22279. get: function () {
  22280. return this._rigCameras;
  22281. },
  22282. enumerable: true,
  22283. configurable: true
  22284. });
  22285. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22286. get: function () {
  22287. return this._rigPostProcess;
  22288. },
  22289. enumerable: true,
  22290. configurable: true
  22291. });
  22292. /**
  22293. * Internal, gets the first post proces.
  22294. * @returns the first post process to be run on this camera.
  22295. */
  22296. Camera.prototype._getFirstPostProcess = function () {
  22297. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22298. if (this._postProcesses[ppIndex] !== null) {
  22299. return this._postProcesses[ppIndex];
  22300. }
  22301. }
  22302. return null;
  22303. };
  22304. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22305. // invalidate framebuffer
  22306. var firstPostProcess = this._getFirstPostProcess();
  22307. if (firstPostProcess) {
  22308. firstPostProcess.markTextureDirty();
  22309. }
  22310. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22311. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22312. var cam = this._rigCameras[i];
  22313. var rigPostProcess = cam._rigPostProcess;
  22314. // for VR rig, there does not have to be a post process
  22315. if (rigPostProcess) {
  22316. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22317. if (isPass) {
  22318. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22319. cam.isIntermediate = this._postProcesses.length === 0;
  22320. }
  22321. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22322. rigPostProcess.markTextureDirty();
  22323. }
  22324. else {
  22325. cam._postProcesses = this._postProcesses.slice(0);
  22326. }
  22327. }
  22328. };
  22329. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22330. if (insertAt === void 0) { insertAt = null; }
  22331. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22332. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22333. return 0;
  22334. }
  22335. if (insertAt == null || insertAt < 0) {
  22336. this._postProcesses.push(postProcess);
  22337. }
  22338. else if (this._postProcesses[insertAt] === null) {
  22339. this._postProcesses[insertAt] = postProcess;
  22340. }
  22341. else {
  22342. this._postProcesses.splice(insertAt, 0, postProcess);
  22343. }
  22344. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22345. return this._postProcesses.indexOf(postProcess);
  22346. };
  22347. Camera.prototype.detachPostProcess = function (postProcess) {
  22348. var idx = this._postProcesses.indexOf(postProcess);
  22349. if (idx !== -1) {
  22350. this._postProcesses[idx] = null;
  22351. }
  22352. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22353. };
  22354. Camera.prototype.getWorldMatrix = function () {
  22355. if (this._isSynchronizedViewMatrix()) {
  22356. return this._worldMatrix;
  22357. }
  22358. // Getting the the view matrix will also compute the world matrix.
  22359. this.getViewMatrix();
  22360. return this._worldMatrix;
  22361. };
  22362. Camera.prototype._getViewMatrix = function () {
  22363. return BABYLON.Matrix.Identity();
  22364. };
  22365. Camera.prototype.getViewMatrix = function (force) {
  22366. if (!force && this._isSynchronizedViewMatrix()) {
  22367. return this._computedViewMatrix;
  22368. }
  22369. this.updateCache();
  22370. this._computedViewMatrix = this._getViewMatrix();
  22371. this._currentRenderId = this.getScene().getRenderId();
  22372. this._childRenderId = this._currentRenderId;
  22373. this._refreshFrustumPlanes = true;
  22374. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22375. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22376. }
  22377. this.onViewMatrixChangedObservable.notifyObservers(this);
  22378. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22379. return this._computedViewMatrix;
  22380. };
  22381. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22382. this._doNotComputeProjectionMatrix = true;
  22383. if (projection !== undefined) {
  22384. this._projectionMatrix = projection;
  22385. }
  22386. };
  22387. ;
  22388. Camera.prototype.unfreezeProjectionMatrix = function () {
  22389. this._doNotComputeProjectionMatrix = false;
  22390. };
  22391. ;
  22392. Camera.prototype.getProjectionMatrix = function (force) {
  22393. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22394. return this._projectionMatrix;
  22395. }
  22396. // Cache
  22397. this._cache.mode = this.mode;
  22398. this._cache.minZ = this.minZ;
  22399. this._cache.maxZ = this.maxZ;
  22400. // Matrix
  22401. this._refreshFrustumPlanes = true;
  22402. var engine = this.getEngine();
  22403. var scene = this.getScene();
  22404. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22405. this._cache.fov = this.fov;
  22406. this._cache.fovMode = this.fovMode;
  22407. this._cache.aspectRatio = engine.getAspectRatio(this);
  22408. if (this.minZ <= 0) {
  22409. this.minZ = 0.1;
  22410. }
  22411. if (scene.useRightHandedSystem) {
  22412. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22413. }
  22414. else {
  22415. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22416. }
  22417. }
  22418. else {
  22419. var halfWidth = engine.getRenderWidth() / 2.0;
  22420. var halfHeight = engine.getRenderHeight() / 2.0;
  22421. if (scene.useRightHandedSystem) {
  22422. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22423. }
  22424. else {
  22425. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22426. }
  22427. this._cache.orthoLeft = this.orthoLeft;
  22428. this._cache.orthoRight = this.orthoRight;
  22429. this._cache.orthoBottom = this.orthoBottom;
  22430. this._cache.orthoTop = this.orthoTop;
  22431. this._cache.renderWidth = engine.getRenderWidth();
  22432. this._cache.renderHeight = engine.getRenderHeight();
  22433. }
  22434. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22435. return this._projectionMatrix;
  22436. };
  22437. Camera.prototype.getTranformationMatrix = function () {
  22438. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22439. return this._transformMatrix;
  22440. };
  22441. Camera.prototype.updateFrustumPlanes = function () {
  22442. if (!this._refreshFrustumPlanes) {
  22443. return;
  22444. }
  22445. this.getTranformationMatrix();
  22446. if (!this._frustumPlanes) {
  22447. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22448. }
  22449. else {
  22450. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22451. }
  22452. this._refreshFrustumPlanes = false;
  22453. };
  22454. Camera.prototype.isInFrustum = function (target) {
  22455. this.updateFrustumPlanes();
  22456. return target.isInFrustum(this._frustumPlanes);
  22457. };
  22458. Camera.prototype.isCompletelyInFrustum = function (target) {
  22459. this.updateFrustumPlanes();
  22460. return target.isCompletelyInFrustum(this._frustumPlanes);
  22461. };
  22462. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22463. if (length === void 0) { length = 100; }
  22464. if (!transform) {
  22465. transform = this.getWorldMatrix();
  22466. }
  22467. if (!origin) {
  22468. origin = this.position;
  22469. }
  22470. var forward = new BABYLON.Vector3(0, 0, 1);
  22471. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22472. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22473. return new BABYLON.Ray(origin, direction, length);
  22474. };
  22475. /**
  22476. * Releases resources associated with this node.
  22477. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22478. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22479. */
  22480. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22481. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22482. // Observables
  22483. this.onViewMatrixChangedObservable.clear();
  22484. this.onProjectionMatrixChangedObservable.clear();
  22485. this.onAfterCheckInputsObservable.clear();
  22486. this.onRestoreStateObservable.clear();
  22487. // Inputs
  22488. if (this.inputs) {
  22489. this.inputs.clear();
  22490. }
  22491. // Animations
  22492. this.getScene().stopAnimation(this);
  22493. // Remove from scene
  22494. this.getScene().removeCamera(this);
  22495. while (this._rigCameras.length > 0) {
  22496. var camera = this._rigCameras.pop();
  22497. if (camera) {
  22498. camera.dispose();
  22499. }
  22500. }
  22501. // Postprocesses
  22502. if (this._rigPostProcess) {
  22503. this._rigPostProcess.dispose(this);
  22504. this._rigPostProcess = null;
  22505. this._postProcesses = [];
  22506. }
  22507. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22508. this._rigPostProcess = null;
  22509. this._postProcesses = [];
  22510. }
  22511. else {
  22512. var i = this._postProcesses.length;
  22513. while (--i >= 0) {
  22514. var postProcess = this._postProcesses[i];
  22515. if (postProcess) {
  22516. postProcess.dispose(this);
  22517. }
  22518. }
  22519. }
  22520. // Render targets
  22521. var i = this.customRenderTargets.length;
  22522. while (--i >= 0) {
  22523. this.customRenderTargets[i].dispose();
  22524. }
  22525. this.customRenderTargets = [];
  22526. // Active Meshes
  22527. this._activeMeshes.dispose();
  22528. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22529. };
  22530. Object.defineProperty(Camera.prototype, "leftCamera", {
  22531. // ---- Camera rigs section ----
  22532. get: function () {
  22533. if (this._rigCameras.length < 1) {
  22534. return null;
  22535. }
  22536. return this._rigCameras[0];
  22537. },
  22538. enumerable: true,
  22539. configurable: true
  22540. });
  22541. Object.defineProperty(Camera.prototype, "rightCamera", {
  22542. get: function () {
  22543. if (this._rigCameras.length < 2) {
  22544. return null;
  22545. }
  22546. return this._rigCameras[1];
  22547. },
  22548. enumerable: true,
  22549. configurable: true
  22550. });
  22551. Camera.prototype.getLeftTarget = function () {
  22552. if (this._rigCameras.length < 1) {
  22553. return null;
  22554. }
  22555. return this._rigCameras[0].getTarget();
  22556. };
  22557. Camera.prototype.getRightTarget = function () {
  22558. if (this._rigCameras.length < 2) {
  22559. return null;
  22560. }
  22561. return this._rigCameras[1].getTarget();
  22562. };
  22563. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22564. if (this.cameraRigMode === mode) {
  22565. return;
  22566. }
  22567. while (this._rigCameras.length > 0) {
  22568. var camera = this._rigCameras.pop();
  22569. if (camera) {
  22570. camera.dispose();
  22571. }
  22572. }
  22573. this.cameraRigMode = mode;
  22574. this._cameraRigParams = {};
  22575. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22576. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22577. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22578. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22579. // create the rig cameras, unless none
  22580. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22581. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22582. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22583. if (leftCamera && rightCamera) {
  22584. this._rigCameras.push(leftCamera);
  22585. this._rigCameras.push(rightCamera);
  22586. }
  22587. }
  22588. switch (this.cameraRigMode) {
  22589. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22590. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22591. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22592. break;
  22593. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22594. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22595. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22596. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22597. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22598. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22599. break;
  22600. case Camera.RIG_MODE_VR:
  22601. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22602. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22603. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22604. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22605. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22606. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22607. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22608. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22609. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22610. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22611. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22612. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22613. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22614. if (metrics.compensateDistortion) {
  22615. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22616. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22617. }
  22618. break;
  22619. case Camera.RIG_MODE_WEBVR:
  22620. if (rigParams.vrDisplay) {
  22621. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22622. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22623. //Left eye
  22624. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22625. this._rigCameras[0].setCameraRigParameter("left", true);
  22626. //leaving this for future reference
  22627. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22628. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22629. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22630. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22631. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22632. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22633. this._rigCameras[0].parent = this;
  22634. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22635. //Right eye
  22636. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22637. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22638. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22639. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22640. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22641. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22642. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22643. this._rigCameras[1].parent = this;
  22644. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22645. if (Camera.UseAlternateWebVRRendering) {
  22646. this._rigCameras[1]._skipRendering = true;
  22647. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22648. }
  22649. }
  22650. break;
  22651. }
  22652. this._cascadePostProcessesToRigCams();
  22653. this.update();
  22654. };
  22655. Camera.prototype._getVRProjectionMatrix = function () {
  22656. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22657. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22658. return this._projectionMatrix;
  22659. };
  22660. Camera.prototype._updateCameraRotationMatrix = function () {
  22661. //Here for WebVR
  22662. };
  22663. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22664. //Here for WebVR
  22665. };
  22666. /**
  22667. * This function MUST be overwritten by the different WebVR cameras available.
  22668. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22669. */
  22670. Camera.prototype._getWebVRProjectionMatrix = function () {
  22671. return BABYLON.Matrix.Identity();
  22672. };
  22673. /**
  22674. * This function MUST be overwritten by the different WebVR cameras available.
  22675. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22676. */
  22677. Camera.prototype._getWebVRViewMatrix = function () {
  22678. return BABYLON.Matrix.Identity();
  22679. };
  22680. Camera.prototype.setCameraRigParameter = function (name, value) {
  22681. if (!this._cameraRigParams) {
  22682. this._cameraRigParams = {};
  22683. }
  22684. this._cameraRigParams[name] = value;
  22685. //provisionnally:
  22686. if (name === "interaxialDistance") {
  22687. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22688. }
  22689. };
  22690. /**
  22691. * needs to be overridden by children so sub has required properties to be copied
  22692. */
  22693. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22694. return null;
  22695. };
  22696. /**
  22697. * May need to be overridden by children
  22698. */
  22699. Camera.prototype._updateRigCameras = function () {
  22700. for (var i = 0; i < this._rigCameras.length; i++) {
  22701. this._rigCameras[i].minZ = this.minZ;
  22702. this._rigCameras[i].maxZ = this.maxZ;
  22703. this._rigCameras[i].fov = this.fov;
  22704. }
  22705. // only update viewport when ANAGLYPH
  22706. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22707. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22708. }
  22709. };
  22710. Camera.prototype._setupInputs = function () {
  22711. };
  22712. Camera.prototype.serialize = function () {
  22713. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22714. // Type
  22715. serializationObject.type = this.getClassName();
  22716. // Parent
  22717. if (this.parent) {
  22718. serializationObject.parentId = this.parent.id;
  22719. }
  22720. if (this.inputs) {
  22721. this.inputs.serialize(serializationObject);
  22722. }
  22723. // Animations
  22724. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22725. serializationObject.ranges = this.serializeAnimationRanges();
  22726. return serializationObject;
  22727. };
  22728. Camera.prototype.clone = function (name) {
  22729. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22730. };
  22731. Camera.prototype.getDirection = function (localAxis) {
  22732. var result = BABYLON.Vector3.Zero();
  22733. this.getDirectionToRef(localAxis, result);
  22734. return result;
  22735. };
  22736. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22737. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22738. };
  22739. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22740. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22741. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22742. switch (type) {
  22743. case "ArcRotateCamera":
  22744. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22745. case "DeviceOrientationCamera":
  22746. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22747. case "FollowCamera":
  22748. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22749. case "ArcFollowCamera":
  22750. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22751. case "GamepadCamera":
  22752. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22753. case "TouchCamera":
  22754. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22755. case "VirtualJoysticksCamera":
  22756. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22757. case "WebVRFreeCamera":
  22758. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22759. case "WebVRGamepadCamera":
  22760. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22761. case "VRDeviceOrientationFreeCamera":
  22762. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22763. case "VRDeviceOrientationGamepadCamera":
  22764. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22765. case "AnaglyphArcRotateCamera":
  22766. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22767. case "AnaglyphFreeCamera":
  22768. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22769. case "AnaglyphGamepadCamera":
  22770. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22771. case "AnaglyphUniversalCamera":
  22772. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22773. case "StereoscopicArcRotateCamera":
  22774. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22775. case "StereoscopicFreeCamera":
  22776. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22777. case "StereoscopicGamepadCamera":
  22778. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22779. case "StereoscopicUniversalCamera":
  22780. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22781. case "FreeCamera": // Forcing Universal here
  22782. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22783. default: // Universal Camera is the default value
  22784. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22785. }
  22786. };
  22787. Camera.prototype.computeWorldMatrix = function () {
  22788. return this.getWorldMatrix();
  22789. };
  22790. Camera.Parse = function (parsedCamera, scene) {
  22791. var type = parsedCamera.type;
  22792. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22793. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22794. // Parent
  22795. if (parsedCamera.parentId) {
  22796. camera._waitingParentId = parsedCamera.parentId;
  22797. }
  22798. //If camera has an input manager, let it parse inputs settings
  22799. if (camera.inputs) {
  22800. camera.inputs.parse(parsedCamera);
  22801. camera._setupInputs();
  22802. }
  22803. if (camera.setPosition) { // need to force position
  22804. camera.position.copyFromFloats(0, 0, 0);
  22805. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22806. }
  22807. // Target
  22808. if (parsedCamera.target) {
  22809. if (camera.setTarget) {
  22810. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22811. }
  22812. }
  22813. // Apply 3d rig, when found
  22814. if (parsedCamera.cameraRigMode) {
  22815. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22816. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22817. }
  22818. // Animations
  22819. if (parsedCamera.animations) {
  22820. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22821. var parsedAnimation = parsedCamera.animations[animationIndex];
  22822. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22823. }
  22824. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22825. }
  22826. if (parsedCamera.autoAnimate) {
  22827. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22828. }
  22829. return camera;
  22830. };
  22831. // Statics
  22832. Camera._PERSPECTIVE_CAMERA = 0;
  22833. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22834. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22835. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22836. Camera._RIG_MODE_NONE = 0;
  22837. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22838. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22839. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22840. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22841. Camera._RIG_MODE_VR = 20;
  22842. Camera._RIG_MODE_WEBVR = 21;
  22843. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22844. Camera.UseAlternateWebVRRendering = false;
  22845. __decorate([
  22846. BABYLON.serializeAsVector3()
  22847. ], Camera.prototype, "position", void 0);
  22848. __decorate([
  22849. BABYLON.serializeAsVector3()
  22850. ], Camera.prototype, "upVector", void 0);
  22851. __decorate([
  22852. BABYLON.serialize()
  22853. ], Camera.prototype, "orthoLeft", void 0);
  22854. __decorate([
  22855. BABYLON.serialize()
  22856. ], Camera.prototype, "orthoRight", void 0);
  22857. __decorate([
  22858. BABYLON.serialize()
  22859. ], Camera.prototype, "orthoBottom", void 0);
  22860. __decorate([
  22861. BABYLON.serialize()
  22862. ], Camera.prototype, "orthoTop", void 0);
  22863. __decorate([
  22864. BABYLON.serialize()
  22865. ], Camera.prototype, "fov", void 0);
  22866. __decorate([
  22867. BABYLON.serialize()
  22868. ], Camera.prototype, "minZ", void 0);
  22869. __decorate([
  22870. BABYLON.serialize()
  22871. ], Camera.prototype, "maxZ", void 0);
  22872. __decorate([
  22873. BABYLON.serialize()
  22874. ], Camera.prototype, "inertia", void 0);
  22875. __decorate([
  22876. BABYLON.serialize()
  22877. ], Camera.prototype, "mode", void 0);
  22878. __decorate([
  22879. BABYLON.serialize()
  22880. ], Camera.prototype, "layerMask", void 0);
  22881. __decorate([
  22882. BABYLON.serialize()
  22883. ], Camera.prototype, "fovMode", void 0);
  22884. __decorate([
  22885. BABYLON.serialize()
  22886. ], Camera.prototype, "cameraRigMode", void 0);
  22887. __decorate([
  22888. BABYLON.serialize()
  22889. ], Camera.prototype, "interaxialDistance", void 0);
  22890. __decorate([
  22891. BABYLON.serialize()
  22892. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22893. return Camera;
  22894. }(BABYLON.Node));
  22895. BABYLON.Camera = Camera;
  22896. })(BABYLON || (BABYLON = {}));
  22897. //# sourceMappingURL=babylon.camera.js.map
  22898. var BABYLON;
  22899. (function (BABYLON) {
  22900. var RenderingManager = /** @class */ (function () {
  22901. function RenderingManager(scene) {
  22902. this._renderingGroups = new Array();
  22903. this._autoClearDepthStencil = {};
  22904. this._customOpaqueSortCompareFn = {};
  22905. this._customAlphaTestSortCompareFn = {};
  22906. this._customTransparentSortCompareFn = {};
  22907. this._renderinGroupInfo = null;
  22908. this._scene = scene;
  22909. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22910. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22911. }
  22912. }
  22913. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22914. if (depth === void 0) { depth = true; }
  22915. if (stencil === void 0) { stencil = true; }
  22916. if (this._depthStencilBufferAlreadyCleaned) {
  22917. return;
  22918. }
  22919. this._scene.getEngine().clear(null, false, depth, stencil);
  22920. this._depthStencilBufferAlreadyCleaned = true;
  22921. };
  22922. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22923. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22924. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22925. var info = null;
  22926. if (observable) {
  22927. if (!this._renderinGroupInfo) {
  22928. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22929. }
  22930. info = this._renderinGroupInfo;
  22931. info.scene = this._scene;
  22932. info.camera = this._scene.activeCamera;
  22933. }
  22934. // Dispatch sprites
  22935. if (renderSprites) {
  22936. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22937. var manager = this._scene.spriteManagers[index];
  22938. this.dispatchSprites(manager);
  22939. }
  22940. }
  22941. // Render
  22942. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22943. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22944. var renderingGroup = this._renderingGroups[index];
  22945. if (!renderingGroup && !observable)
  22946. continue;
  22947. var renderingGroupMask = 0;
  22948. // Fire PRECLEAR stage
  22949. if (observable && info) {
  22950. renderingGroupMask = Math.pow(2, index);
  22951. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22952. info.renderingGroupId = index;
  22953. observable.notifyObservers(info, renderingGroupMask);
  22954. }
  22955. // Clear depth/stencil if needed
  22956. if (RenderingManager.AUTOCLEAR) {
  22957. var autoClear = this._autoClearDepthStencil[index];
  22958. if (autoClear && autoClear.autoClear) {
  22959. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22960. }
  22961. }
  22962. if (observable && info) {
  22963. // Fire PREOPAQUE stage
  22964. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22965. observable.notifyObservers(info, renderingGroupMask);
  22966. // Fire PRETRANSPARENT stage
  22967. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22968. observable.notifyObservers(info, renderingGroupMask);
  22969. }
  22970. if (renderingGroup)
  22971. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22972. // Fire POSTTRANSPARENT stage
  22973. if (observable && info) {
  22974. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22975. observable.notifyObservers(info, renderingGroupMask);
  22976. }
  22977. }
  22978. };
  22979. RenderingManager.prototype.reset = function () {
  22980. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22981. var renderingGroup = this._renderingGroups[index];
  22982. if (renderingGroup) {
  22983. renderingGroup.prepare();
  22984. }
  22985. }
  22986. };
  22987. RenderingManager.prototype.dispose = function () {
  22988. this.freeRenderingGroups();
  22989. this._renderingGroups.length = 0;
  22990. };
  22991. /**
  22992. * Clear the info related to rendering groups preventing retention points during dispose.
  22993. */
  22994. RenderingManager.prototype.freeRenderingGroups = function () {
  22995. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22996. var renderingGroup = this._renderingGroups[index];
  22997. if (renderingGroup) {
  22998. renderingGroup.dispose();
  22999. }
  23000. }
  23001. };
  23002. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23003. if (this._renderingGroups[renderingGroupId] === undefined) {
  23004. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23005. }
  23006. };
  23007. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23008. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23009. this._prepareRenderingGroup(renderingGroupId);
  23010. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23011. };
  23012. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23013. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23014. this._prepareRenderingGroup(renderingGroupId);
  23015. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23016. };
  23017. /**
  23018. * @param subMesh The submesh to dispatch
  23019. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23020. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23021. */
  23022. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23023. if (mesh === undefined) {
  23024. mesh = subMesh.getMesh();
  23025. }
  23026. var renderingGroupId = mesh.renderingGroupId || 0;
  23027. this._prepareRenderingGroup(renderingGroupId);
  23028. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23029. };
  23030. /**
  23031. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23032. * This allowed control for front to back rendering or reversly depending of the special needs.
  23033. *
  23034. * @param renderingGroupId The rendering group id corresponding to its index
  23035. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23036. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23037. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23038. */
  23039. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23040. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23041. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23042. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23043. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23044. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23045. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23046. if (this._renderingGroups[renderingGroupId]) {
  23047. var group = this._renderingGroups[renderingGroupId];
  23048. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23049. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23050. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23051. }
  23052. };
  23053. /**
  23054. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23055. *
  23056. * @param renderingGroupId The rendering group id corresponding to its index
  23057. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23058. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23059. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23060. */
  23061. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23062. if (depth === void 0) { depth = true; }
  23063. if (stencil === void 0) { stencil = true; }
  23064. this._autoClearDepthStencil[renderingGroupId] = {
  23065. autoClear: autoClearDepthStencil,
  23066. depth: depth,
  23067. stencil: stencil
  23068. };
  23069. };
  23070. /**
  23071. * The max id used for rendering groups (not included)
  23072. */
  23073. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23074. /**
  23075. * The min id used for rendering groups (included)
  23076. */
  23077. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23078. /**
  23079. * Used to globally prevent autoclearing scenes.
  23080. */
  23081. RenderingManager.AUTOCLEAR = true;
  23082. return RenderingManager;
  23083. }());
  23084. BABYLON.RenderingManager = RenderingManager;
  23085. })(BABYLON || (BABYLON = {}));
  23086. //# sourceMappingURL=babylon.renderingManager.js.map
  23087. var BABYLON;
  23088. (function (BABYLON) {
  23089. var RenderingGroup = /** @class */ (function () {
  23090. /**
  23091. * Creates a new rendering group.
  23092. * @param index The rendering group index
  23093. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23094. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23095. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23096. */
  23097. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23098. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23099. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23100. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23101. this.index = index;
  23102. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23103. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23104. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23105. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23106. this._particleSystems = new BABYLON.SmartArray(256);
  23107. this._spriteManagers = new BABYLON.SmartArray(256);
  23108. this._edgesRenderers = new BABYLON.SmartArray(16);
  23109. this._scene = scene;
  23110. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23111. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23112. this.transparentSortCompareFn = transparentSortCompareFn;
  23113. }
  23114. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23115. /**
  23116. * Set the opaque sort comparison function.
  23117. * If null the sub meshes will be render in the order they were created
  23118. */
  23119. set: function (value) {
  23120. this._opaqueSortCompareFn = value;
  23121. if (value) {
  23122. this._renderOpaque = this.renderOpaqueSorted;
  23123. }
  23124. else {
  23125. this._renderOpaque = RenderingGroup.renderUnsorted;
  23126. }
  23127. },
  23128. enumerable: true,
  23129. configurable: true
  23130. });
  23131. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23132. /**
  23133. * Set the alpha test sort comparison function.
  23134. * If null the sub meshes will be render in the order they were created
  23135. */
  23136. set: function (value) {
  23137. this._alphaTestSortCompareFn = value;
  23138. if (value) {
  23139. this._renderAlphaTest = this.renderAlphaTestSorted;
  23140. }
  23141. else {
  23142. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23143. }
  23144. },
  23145. enumerable: true,
  23146. configurable: true
  23147. });
  23148. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23149. /**
  23150. * Set the transparent sort comparison function.
  23151. * If null the sub meshes will be render in the order they were created
  23152. */
  23153. set: function (value) {
  23154. if (value) {
  23155. this._transparentSortCompareFn = value;
  23156. }
  23157. else {
  23158. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23159. }
  23160. this._renderTransparent = this.renderTransparentSorted;
  23161. },
  23162. enumerable: true,
  23163. configurable: true
  23164. });
  23165. /**
  23166. * Render all the sub meshes contained in the group.
  23167. * @param customRenderFunction Used to override the default render behaviour of the group.
  23168. * @returns true if rendered some submeshes.
  23169. */
  23170. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23171. if (customRenderFunction) {
  23172. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23173. return;
  23174. }
  23175. var engine = this._scene.getEngine();
  23176. // Depth only
  23177. if (this._depthOnlySubMeshes.length !== 0) {
  23178. engine.setColorWrite(false);
  23179. this._renderAlphaTest(this._depthOnlySubMeshes);
  23180. engine.setColorWrite(true);
  23181. }
  23182. // Opaque
  23183. if (this._opaqueSubMeshes.length !== 0) {
  23184. this._renderOpaque(this._opaqueSubMeshes);
  23185. }
  23186. // Alpha test
  23187. if (this._alphaTestSubMeshes.length !== 0) {
  23188. this._renderAlphaTest(this._alphaTestSubMeshes);
  23189. }
  23190. var stencilState = engine.getStencilBuffer();
  23191. engine.setStencilBuffer(false);
  23192. // Sprites
  23193. if (renderSprites) {
  23194. this._renderSprites();
  23195. }
  23196. // Particles
  23197. if (renderParticles) {
  23198. this._renderParticles(activeMeshes);
  23199. }
  23200. if (this.onBeforeTransparentRendering) {
  23201. this.onBeforeTransparentRendering();
  23202. }
  23203. // Transparent
  23204. if (this._transparentSubMeshes.length !== 0) {
  23205. this._renderTransparent(this._transparentSubMeshes);
  23206. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23207. }
  23208. // Set back stencil to false in case it changes before the edge renderer.
  23209. engine.setStencilBuffer(false);
  23210. // Edges
  23211. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23212. this._edgesRenderers.data[edgesRendererIndex].render();
  23213. }
  23214. // Restore Stencil state.
  23215. engine.setStencilBuffer(stencilState);
  23216. };
  23217. /**
  23218. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23219. * @param subMeshes The submeshes to render
  23220. */
  23221. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23222. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23223. };
  23224. /**
  23225. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23226. * @param subMeshes The submeshes to render
  23227. */
  23228. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23229. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23230. };
  23231. /**
  23232. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23233. * @param subMeshes The submeshes to render
  23234. */
  23235. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23236. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23237. };
  23238. /**
  23239. * Renders the submeshes in a specified order.
  23240. * @param subMeshes The submeshes to sort before render
  23241. * @param sortCompareFn The comparison function use to sort
  23242. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23243. * @param transparent Specifies to activate blending if true
  23244. */
  23245. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23246. var subIndex = 0;
  23247. var subMesh;
  23248. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23249. for (; subIndex < subMeshes.length; subIndex++) {
  23250. subMesh = subMeshes.data[subIndex];
  23251. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23252. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23253. }
  23254. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23255. if (sortCompareFn) {
  23256. sortedArray.sort(sortCompareFn);
  23257. }
  23258. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23259. subMesh = sortedArray[subIndex];
  23260. if (transparent) {
  23261. var material = subMesh.getMaterial();
  23262. if (material && material.needDepthPrePass) {
  23263. var engine = material.getScene().getEngine();
  23264. engine.setColorWrite(false);
  23265. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23266. subMesh.render(false);
  23267. engine.setColorWrite(true);
  23268. }
  23269. }
  23270. subMesh.render(transparent);
  23271. }
  23272. };
  23273. /**
  23274. * Renders the submeshes in the order they were dispatched (no sort applied).
  23275. * @param subMeshes The submeshes to render
  23276. */
  23277. RenderingGroup.renderUnsorted = function (subMeshes) {
  23278. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23279. var submesh = subMeshes.data[subIndex];
  23280. submesh.render(false);
  23281. }
  23282. };
  23283. /**
  23284. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23285. * are rendered back to front if in the same alpha index.
  23286. *
  23287. * @param a The first submesh
  23288. * @param b The second submesh
  23289. * @returns The result of the comparison
  23290. */
  23291. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23292. // Alpha index first
  23293. if (a._alphaIndex > b._alphaIndex) {
  23294. return 1;
  23295. }
  23296. if (a._alphaIndex < b._alphaIndex) {
  23297. return -1;
  23298. }
  23299. // Then distance to camera
  23300. return RenderingGroup.backToFrontSortCompare(a, b);
  23301. };
  23302. /**
  23303. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23304. * are rendered back to front.
  23305. *
  23306. * @param a The first submesh
  23307. * @param b The second submesh
  23308. * @returns The result of the comparison
  23309. */
  23310. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23311. // Then distance to camera
  23312. if (a._distanceToCamera < b._distanceToCamera) {
  23313. return 1;
  23314. }
  23315. if (a._distanceToCamera > b._distanceToCamera) {
  23316. return -1;
  23317. }
  23318. return 0;
  23319. };
  23320. /**
  23321. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23322. * are rendered front to back (prevent overdraw).
  23323. *
  23324. * @param a The first submesh
  23325. * @param b The second submesh
  23326. * @returns The result of the comparison
  23327. */
  23328. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23329. // Then distance to camera
  23330. if (a._distanceToCamera < b._distanceToCamera) {
  23331. return -1;
  23332. }
  23333. if (a._distanceToCamera > b._distanceToCamera) {
  23334. return 1;
  23335. }
  23336. return 0;
  23337. };
  23338. /**
  23339. * Resets the different lists of submeshes to prepare a new frame.
  23340. */
  23341. RenderingGroup.prototype.prepare = function () {
  23342. this._opaqueSubMeshes.reset();
  23343. this._transparentSubMeshes.reset();
  23344. this._alphaTestSubMeshes.reset();
  23345. this._depthOnlySubMeshes.reset();
  23346. this._particleSystems.reset();
  23347. this._spriteManagers.reset();
  23348. this._edgesRenderers.reset();
  23349. };
  23350. RenderingGroup.prototype.dispose = function () {
  23351. this._opaqueSubMeshes.dispose();
  23352. this._transparentSubMeshes.dispose();
  23353. this._alphaTestSubMeshes.dispose();
  23354. this._depthOnlySubMeshes.dispose();
  23355. this._particleSystems.dispose();
  23356. this._spriteManagers.dispose();
  23357. this._edgesRenderers.dispose();
  23358. };
  23359. /**
  23360. * Inserts the submesh in its correct queue depending on its material.
  23361. * @param subMesh The submesh to dispatch
  23362. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23363. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23364. */
  23365. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23366. // Get mesh and materials if not provided
  23367. if (mesh === undefined) {
  23368. mesh = subMesh.getMesh();
  23369. }
  23370. if (material === undefined) {
  23371. material = subMesh.getMaterial();
  23372. }
  23373. if (material === null || material === undefined) {
  23374. return;
  23375. }
  23376. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23377. this._transparentSubMeshes.push(subMesh);
  23378. }
  23379. else if (material.needAlphaTesting()) { // Alpha test
  23380. if (material.needDepthPrePass) {
  23381. this._depthOnlySubMeshes.push(subMesh);
  23382. }
  23383. this._alphaTestSubMeshes.push(subMesh);
  23384. }
  23385. else {
  23386. if (material.needDepthPrePass) {
  23387. this._depthOnlySubMeshes.push(subMesh);
  23388. }
  23389. this._opaqueSubMeshes.push(subMesh); // Opaque
  23390. }
  23391. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23392. this._edgesRenderers.push(mesh._edgesRenderer);
  23393. }
  23394. };
  23395. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23396. this._spriteManagers.push(spriteManager);
  23397. };
  23398. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23399. this._particleSystems.push(particleSystem);
  23400. };
  23401. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23402. if (this._particleSystems.length === 0) {
  23403. return;
  23404. }
  23405. // Particles
  23406. var activeCamera = this._scene.activeCamera;
  23407. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23408. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23409. var particleSystem = this._particleSystems.data[particleIndex];
  23410. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23411. continue;
  23412. }
  23413. var emitter = particleSystem.emitter;
  23414. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23415. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23416. }
  23417. }
  23418. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23419. };
  23420. RenderingGroup.prototype._renderSprites = function () {
  23421. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23422. return;
  23423. }
  23424. // Sprites
  23425. var activeCamera = this._scene.activeCamera;
  23426. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23427. for (var id = 0; id < this._spriteManagers.length; id++) {
  23428. var spriteManager = this._spriteManagers.data[id];
  23429. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23430. spriteManager.render();
  23431. }
  23432. }
  23433. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23434. };
  23435. return RenderingGroup;
  23436. }());
  23437. BABYLON.RenderingGroup = RenderingGroup;
  23438. })(BABYLON || (BABYLON = {}));
  23439. //# sourceMappingURL=babylon.renderingGroup.js.map
  23440. var BABYLON;
  23441. (function (BABYLON) {
  23442. /** @hidden */
  23443. var ClickInfo = /** @class */ (function () {
  23444. function ClickInfo() {
  23445. this._singleClick = false;
  23446. this._doubleClick = false;
  23447. this._hasSwiped = false;
  23448. this._ignore = false;
  23449. }
  23450. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23451. get: function () {
  23452. return this._singleClick;
  23453. },
  23454. set: function (b) {
  23455. this._singleClick = b;
  23456. },
  23457. enumerable: true,
  23458. configurable: true
  23459. });
  23460. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23461. get: function () {
  23462. return this._doubleClick;
  23463. },
  23464. set: function (b) {
  23465. this._doubleClick = b;
  23466. },
  23467. enumerable: true,
  23468. configurable: true
  23469. });
  23470. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23471. get: function () {
  23472. return this._hasSwiped;
  23473. },
  23474. set: function (b) {
  23475. this._hasSwiped = b;
  23476. },
  23477. enumerable: true,
  23478. configurable: true
  23479. });
  23480. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23481. get: function () {
  23482. return this._ignore;
  23483. },
  23484. set: function (b) {
  23485. this._ignore = b;
  23486. },
  23487. enumerable: true,
  23488. configurable: true
  23489. });
  23490. return ClickInfo;
  23491. }());
  23492. /**
  23493. * This class is used by the onRenderingGroupObservable
  23494. */
  23495. var RenderingGroupInfo = /** @class */ (function () {
  23496. function RenderingGroupInfo() {
  23497. }
  23498. /**
  23499. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23500. * This stage will be fired no matter what
  23501. */
  23502. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23503. /**
  23504. * Called before opaque object are rendered.
  23505. * This stage will be fired only if there's 3D Opaque content to render
  23506. */
  23507. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23508. /**
  23509. * Called after the opaque objects are rendered and before the transparent ones
  23510. * This stage will be fired only if there's 3D transparent content to render
  23511. */
  23512. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23513. /**
  23514. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23515. * This stage will be fired no matter what
  23516. */
  23517. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23518. return RenderingGroupInfo;
  23519. }());
  23520. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23521. /**
  23522. * Represents a scene to be rendered by the engine.
  23523. * @see http://doc.babylonjs.com/features/scene
  23524. */
  23525. var Scene = /** @class */ (function () {
  23526. /**
  23527. * Creates a new Scene
  23528. * @param engine defines the engine to use to render this scene
  23529. */
  23530. function Scene(engine) {
  23531. // Members
  23532. /**
  23533. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23534. */
  23535. this.autoClear = true;
  23536. /**
  23537. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23538. */
  23539. this.autoClearDepthAndStencil = true;
  23540. /**
  23541. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23542. */
  23543. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23544. /**
  23545. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23546. */
  23547. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23548. this._forceWireframe = false;
  23549. this._forcePointsCloud = false;
  23550. /**
  23551. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23552. */
  23553. this.forceShowBoundingBoxes = false;
  23554. /**
  23555. * Gets or sets a boolean indicating if animations are enabled
  23556. */
  23557. this.animationsEnabled = true;
  23558. this._animationPropertiesOverride = null;
  23559. /**
  23560. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23561. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23562. */
  23563. this.useConstantAnimationDeltaTime = false;
  23564. /**
  23565. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23566. * Please note that it requires to run a ray cast through the scene on every frame
  23567. */
  23568. this.constantlyUpdateMeshUnderPointer = false;
  23569. /**
  23570. * Defines the HTML cursor to use when hovering over interactive elements
  23571. */
  23572. this.hoverCursor = "pointer";
  23573. /**
  23574. * Defines the HTML default cursor to use (empty by default)
  23575. */
  23576. this.defaultCursor = "";
  23577. /**
  23578. * This is used to call preventDefault() on pointer down
  23579. * in order to block unwanted artifacts like system double clicks
  23580. */
  23581. this.preventDefaultOnPointerDown = true;
  23582. // Metadata
  23583. /**
  23584. * Gets or sets user defined metadata
  23585. */
  23586. this.metadata = null;
  23587. /**
  23588. * Use this array to add regular expressions used to disable offline support for specific urls
  23589. */
  23590. this.disableOfflineSupportExceptionRules = new Array();
  23591. /**
  23592. * An event triggered when the scene is disposed.
  23593. */
  23594. this.onDisposeObservable = new BABYLON.Observable();
  23595. this._onDisposeObserver = null;
  23596. /**
  23597. * An event triggered before rendering the scene (right after animations and physics)
  23598. */
  23599. this.onBeforeRenderObservable = new BABYLON.Observable();
  23600. this._onBeforeRenderObserver = null;
  23601. /**
  23602. * An event triggered after rendering the scene
  23603. */
  23604. this.onAfterRenderObservable = new BABYLON.Observable();
  23605. this._onAfterRenderObserver = null;
  23606. /**
  23607. * An event triggered before animating the scene
  23608. */
  23609. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23610. /**
  23611. * An event triggered after animations processing
  23612. */
  23613. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23614. /**
  23615. * An event triggered before draw calls are ready to be sent
  23616. */
  23617. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23618. /**
  23619. * An event triggered after draw calls have been sent
  23620. */
  23621. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23622. /**
  23623. * An event triggered when physic simulation is about to be run
  23624. */
  23625. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23626. /**
  23627. * An event triggered when physic simulation has been done
  23628. */
  23629. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23630. /**
  23631. * An event triggered when the scene is ready
  23632. */
  23633. this.onReadyObservable = new BABYLON.Observable();
  23634. /**
  23635. * An event triggered before rendering a camera
  23636. */
  23637. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23638. this._onBeforeCameraRenderObserver = null;
  23639. /**
  23640. * An event triggered after rendering a camera
  23641. */
  23642. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23643. this._onAfterCameraRenderObserver = null;
  23644. /**
  23645. * An event triggered when active meshes evaluation is about to start
  23646. */
  23647. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23648. /**
  23649. * An event triggered when active meshes evaluation is done
  23650. */
  23651. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23652. /**
  23653. * An event triggered when particles rendering is about to start
  23654. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23655. */
  23656. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23657. /**
  23658. * An event triggered when particles rendering is done
  23659. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23660. */
  23661. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23662. /**
  23663. * An event triggered when sprites rendering is about to start
  23664. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23665. */
  23666. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23667. /**
  23668. * An event triggered when sprites rendering is done
  23669. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23670. */
  23671. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23672. /**
  23673. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23674. */
  23675. this.onDataLoadedObservable = new BABYLON.Observable();
  23676. /**
  23677. * An event triggered when a camera is created
  23678. */
  23679. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23680. /**
  23681. * An event triggered when a camera is removed
  23682. */
  23683. this.onCameraRemovedObservable = new BABYLON.Observable();
  23684. /**
  23685. * An event triggered when a light is created
  23686. */
  23687. this.onNewLightAddedObservable = new BABYLON.Observable();
  23688. /**
  23689. * An event triggered when a light is removed
  23690. */
  23691. this.onLightRemovedObservable = new BABYLON.Observable();
  23692. /**
  23693. * An event triggered when a geometry is created
  23694. */
  23695. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23696. /**
  23697. * An event triggered when a geometry is removed
  23698. */
  23699. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23700. /**
  23701. * An event triggered when a transform node is created
  23702. */
  23703. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23704. /**
  23705. * An event triggered when a transform node is removed
  23706. */
  23707. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23708. /**
  23709. * An event triggered when a mesh is created
  23710. */
  23711. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23712. /**
  23713. * An event triggered when a mesh is removed
  23714. */
  23715. this.onMeshRemovedObservable = new BABYLON.Observable();
  23716. /**
  23717. * An event triggered when render targets are about to be rendered
  23718. * Can happen multiple times per frame.
  23719. */
  23720. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23721. /**
  23722. * An event triggered when render targets were rendered.
  23723. * Can happen multiple times per frame.
  23724. */
  23725. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23726. /**
  23727. * An event triggered before calculating deterministic simulation step
  23728. */
  23729. this.onBeforeStepObservable = new BABYLON.Observable();
  23730. /**
  23731. * An event triggered after calculating deterministic simulation step
  23732. */
  23733. this.onAfterStepObservable = new BABYLON.Observable();
  23734. /**
  23735. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23736. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23737. * 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)
  23738. */
  23739. this.onRenderingGroupObservable = new BABYLON.Observable();
  23740. // Animations
  23741. /**
  23742. * Gets a list of Animations associated with the scene
  23743. */
  23744. this.animations = [];
  23745. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23746. /**
  23747. * 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).
  23748. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23749. */
  23750. this.onPrePointerObservable = new BABYLON.Observable();
  23751. /**
  23752. * Observable event triggered each time an input event is received from the rendering canvas
  23753. */
  23754. this.onPointerObservable = new BABYLON.Observable();
  23755. this._meshPickProceed = false;
  23756. this._currentPickResult = null;
  23757. this._previousPickResult = null;
  23758. this._totalPointersPressed = 0;
  23759. this._doubleClickOccured = false;
  23760. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23761. this.cameraToUseForPointers = null;
  23762. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23763. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23764. this._startingPointerTime = 0;
  23765. this._previousStartingPointerTime = 0;
  23766. // Deterministic lockstep
  23767. this._timeAccumulator = 0;
  23768. this._currentStepId = 0;
  23769. this._currentInternalStep = 0;
  23770. // Keyboard
  23771. /**
  23772. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23773. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23774. */
  23775. this.onPreKeyboardObservable = new BABYLON.Observable();
  23776. /**
  23777. * Observable event triggered each time an keyboard event is received from the hosting window
  23778. */
  23779. this.onKeyboardObservable = new BABYLON.Observable();
  23780. // Coordinates system
  23781. this._useRightHandedSystem = false;
  23782. // Fog
  23783. this._fogEnabled = true;
  23784. this._fogMode = Scene.FOGMODE_NONE;
  23785. /**
  23786. * Gets or sets the fog color to use
  23787. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23788. */
  23789. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23790. /**
  23791. * Gets or sets the fog density to use
  23792. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23793. */
  23794. this.fogDensity = 0.1;
  23795. /**
  23796. * Gets or sets the fog start distance to use
  23797. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23798. */
  23799. this.fogStart = 0;
  23800. /**
  23801. * Gets or sets the fog end distance to use
  23802. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23803. */
  23804. this.fogEnd = 1000.0;
  23805. // Lights
  23806. this._shadowsEnabled = true;
  23807. this._lightsEnabled = true;
  23808. /**
  23809. * All of the lights added to this scene
  23810. * @see http://doc.babylonjs.com/babylon101/lights
  23811. */
  23812. this.lights = new Array();
  23813. // Cameras
  23814. /** All of the cameras added to this scene.
  23815. * @see http://doc.babylonjs.com/babylon101/cameras
  23816. */
  23817. this.cameras = new Array();
  23818. /** All of the active cameras added to this scene. */
  23819. this.activeCameras = new Array();
  23820. // Meshes
  23821. /**
  23822. * All of the tranform nodes added to this scene
  23823. * @see http://doc.babylonjs.com/how_to/transformnode
  23824. */
  23825. this.transformNodes = new Array();
  23826. /**
  23827. * All of the (abstract) meshes added to this scene
  23828. */
  23829. this.meshes = new Array();
  23830. /**
  23831. * All of the animation groups added to this scene
  23832. * @see http://doc.babylonjs.com/how_to/group
  23833. */
  23834. this.animationGroups = new Array();
  23835. // Geometries
  23836. this._geometries = new Array();
  23837. /**
  23838. * All of the materials added to this scene
  23839. * @see http://doc.babylonjs.com/babylon101/materials
  23840. */
  23841. this.materials = new Array();
  23842. /**
  23843. * All of the multi-materials added to this scene
  23844. * @see http://doc.babylonjs.com/how_to/multi_materials
  23845. */
  23846. this.multiMaterials = new Array();
  23847. // Textures
  23848. this._texturesEnabled = true;
  23849. /**
  23850. * All of the textures added to this scene
  23851. */
  23852. this.textures = new Array();
  23853. // Particles
  23854. /**
  23855. * Gets or sets a boolean indicating if particles are enabled on this scene
  23856. */
  23857. this.particlesEnabled = true;
  23858. /**
  23859. * All of the particle systems added to this scene
  23860. * @see http://doc.babylonjs.com/babylon101/particles
  23861. */
  23862. this.particleSystems = new Array();
  23863. // Sprites
  23864. /**
  23865. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23866. */
  23867. this.spritesEnabled = true;
  23868. /**
  23869. * All of the sprite managers added to this scene
  23870. * @see http://doc.babylonjs.com/babylon101/sprites
  23871. */
  23872. this.spriteManagers = new Array();
  23873. /**
  23874. * The list of layers (background and foreground) of the scene
  23875. */
  23876. this.layers = new Array();
  23877. /**
  23878. * The list of effect layers (highlights/glow) added to the scene
  23879. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23880. * @see http://doc.babylonjs.com/how_to/glow_layer
  23881. */
  23882. this.effectLayers = new Array();
  23883. // Skeletons
  23884. this._skeletonsEnabled = true;
  23885. /**
  23886. * The list of skeletons added to the scene
  23887. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23888. */
  23889. this.skeletons = new Array();
  23890. // Morph targets
  23891. /**
  23892. * The list of morph target managers added to the scene
  23893. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23894. */
  23895. this.morphTargetManagers = new Array();
  23896. // Lens flares
  23897. /**
  23898. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23899. */
  23900. this.lensFlaresEnabled = true;
  23901. /**
  23902. * The list of lens flare system added to the scene
  23903. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23904. */
  23905. this.lensFlareSystems = new Array();
  23906. // Collisions
  23907. /**
  23908. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23909. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23910. */
  23911. this.collisionsEnabled = true;
  23912. /**
  23913. * Defines the gravity applied to this scene (used only for collisions)
  23914. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23915. */
  23916. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23917. // Postprocesses
  23918. /**
  23919. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23920. */
  23921. this.postProcessesEnabled = true;
  23922. /**
  23923. * The list of postprocesses added to the scene
  23924. */
  23925. this.postProcesses = new Array();
  23926. // Customs render targets
  23927. /**
  23928. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23929. */
  23930. this.renderTargetsEnabled = true;
  23931. /**
  23932. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23933. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23934. */
  23935. this.dumpNextRenderTargets = false;
  23936. /**
  23937. * The list of user defined render targets added to the scene
  23938. */
  23939. this.customRenderTargets = new Array();
  23940. /**
  23941. * Gets the list of meshes imported to the scene through SceneLoader
  23942. */
  23943. this.importedMeshesFiles = new Array();
  23944. // Probes
  23945. /**
  23946. * Gets or sets a boolean indicating if probes are enabled on this scene
  23947. */
  23948. this.probesEnabled = true;
  23949. /**
  23950. * The list of reflection probes added to the scene
  23951. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23952. */
  23953. this.reflectionProbes = new Array();
  23954. /** @hidden */
  23955. this._actionManagers = new Array();
  23956. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23957. // Procedural textures
  23958. /**
  23959. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23960. */
  23961. this.proceduralTexturesEnabled = true;
  23962. /**
  23963. * The list of procedural textures added to the scene
  23964. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23965. */
  23966. this.proceduralTextures = new Array();
  23967. /**
  23968. * The list of sound tracks added to the scene
  23969. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23970. */
  23971. this.soundTracks = new Array();
  23972. this._audioEnabled = true;
  23973. this._headphone = false;
  23974. // Performance counters
  23975. this._totalVertices = new BABYLON.PerfCounter();
  23976. /** @hidden */
  23977. this._activeIndices = new BABYLON.PerfCounter();
  23978. /** @hidden */
  23979. this._activeParticles = new BABYLON.PerfCounter();
  23980. /** @hidden */
  23981. this._activeBones = new BABYLON.PerfCounter();
  23982. this._animationTime = 0;
  23983. /**
  23984. * Gets or sets a general scale for animation speed
  23985. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23986. */
  23987. this.animationTimeScale = 1;
  23988. this._renderId = 0;
  23989. this._executeWhenReadyTimeoutId = -1;
  23990. this._intermediateRendering = false;
  23991. this._viewUpdateFlag = -1;
  23992. this._projectionUpdateFlag = -1;
  23993. this._alternateViewUpdateFlag = -1;
  23994. this._alternateProjectionUpdateFlag = -1;
  23995. /** @hidden */
  23996. this._toBeDisposed = new BABYLON.SmartArray(256);
  23997. this._activeRequests = new Array();
  23998. this._pendingData = new Array();
  23999. this._isDisposed = false;
  24000. /**
  24001. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24002. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24003. */
  24004. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24005. this._activeMeshes = new BABYLON.SmartArray(256);
  24006. this._processedMaterials = new BABYLON.SmartArray(256);
  24007. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24008. /** @hidden */
  24009. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24010. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24011. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24012. /** @hidden */
  24013. this._activeAnimatables = new Array();
  24014. this._transformMatrix = BABYLON.Matrix.Zero();
  24015. this._useAlternateCameraConfiguration = false;
  24016. this._alternateRendering = false;
  24017. /**
  24018. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24019. * This is useful if there are more lights that the maximum simulteanous authorized
  24020. */
  24021. this.requireLightSorting = false;
  24022. this._depthRenderer = {};
  24023. this._activeMeshesFrozen = false;
  24024. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24025. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24026. this._engine.scenes.push(this);
  24027. this._uid = null;
  24028. this._renderingManager = new BABYLON.RenderingManager(this);
  24029. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24030. if (BABYLON.OutlineRenderer) {
  24031. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24032. }
  24033. if (BABYLON.Tools.IsWindowObjectExist()) {
  24034. this.attachControl();
  24035. }
  24036. //simplification queue
  24037. if (BABYLON.SimplificationQueue) {
  24038. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24039. }
  24040. //collision coordinator initialization. For now legacy per default.
  24041. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24042. // Uniform Buffer
  24043. this._createUbo();
  24044. // Default Image processing definition.
  24045. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24046. }
  24047. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24048. /** The fog is deactivated */
  24049. get: function () {
  24050. return Scene._FOGMODE_NONE;
  24051. },
  24052. enumerable: true,
  24053. configurable: true
  24054. });
  24055. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24056. /** The fog density is following an exponential function */
  24057. get: function () {
  24058. return Scene._FOGMODE_EXP;
  24059. },
  24060. enumerable: true,
  24061. configurable: true
  24062. });
  24063. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24064. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24065. get: function () {
  24066. return Scene._FOGMODE_EXP2;
  24067. },
  24068. enumerable: true,
  24069. configurable: true
  24070. });
  24071. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24072. /** The fog density is following a linear function. */
  24073. get: function () {
  24074. return Scene._FOGMODE_LINEAR;
  24075. },
  24076. enumerable: true,
  24077. configurable: true
  24078. });
  24079. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24080. /**
  24081. * Texture used in all pbr material as the reflection texture.
  24082. * As in the majority of the scene they are the same (exception for multi room and so on),
  24083. * this is easier to reference from here than from all the materials.
  24084. */
  24085. get: function () {
  24086. return this._environmentTexture;
  24087. },
  24088. /**
  24089. * Texture used in all pbr material as the reflection texture.
  24090. * As in the majority of the scene they are the same (exception for multi room and so on),
  24091. * this is easier to set here than in all the materials.
  24092. */
  24093. set: function (value) {
  24094. if (this._environmentTexture === value) {
  24095. return;
  24096. }
  24097. this._environmentTexture = value;
  24098. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24099. },
  24100. enumerable: true,
  24101. configurable: true
  24102. });
  24103. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24104. /**
  24105. * Default image processing configuration used either in the rendering
  24106. * Forward main pass or through the imageProcessingPostProcess if present.
  24107. * As in the majority of the scene they are the same (exception for multi camera),
  24108. * this is easier to reference from here than from all the materials and post process.
  24109. *
  24110. * No setter as we it is a shared configuration, you can set the values instead.
  24111. */
  24112. get: function () {
  24113. return this._imageProcessingConfiguration;
  24114. },
  24115. enumerable: true,
  24116. configurable: true
  24117. });
  24118. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24119. get: function () {
  24120. return this._forceWireframe;
  24121. },
  24122. /**
  24123. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24124. */
  24125. set: function (value) {
  24126. if (this._forceWireframe === value) {
  24127. return;
  24128. }
  24129. this._forceWireframe = value;
  24130. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24131. },
  24132. enumerable: true,
  24133. configurable: true
  24134. });
  24135. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24136. get: function () {
  24137. return this._forcePointsCloud;
  24138. },
  24139. /**
  24140. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24141. */
  24142. set: function (value) {
  24143. if (this._forcePointsCloud === value) {
  24144. return;
  24145. }
  24146. this._forcePointsCloud = value;
  24147. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24148. },
  24149. enumerable: true,
  24150. configurable: true
  24151. });
  24152. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24153. /**
  24154. * Gets or sets the animation properties override
  24155. */
  24156. get: function () {
  24157. return this._animationPropertiesOverride;
  24158. },
  24159. set: function (value) {
  24160. this._animationPropertiesOverride = value;
  24161. },
  24162. enumerable: true,
  24163. configurable: true
  24164. });
  24165. Object.defineProperty(Scene.prototype, "onDispose", {
  24166. /** Sets a function to be executed when this scene is disposed. */
  24167. set: function (callback) {
  24168. if (this._onDisposeObserver) {
  24169. this.onDisposeObservable.remove(this._onDisposeObserver);
  24170. }
  24171. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24172. },
  24173. enumerable: true,
  24174. configurable: true
  24175. });
  24176. Object.defineProperty(Scene.prototype, "beforeRender", {
  24177. /** Sets a function to be executed before rendering this scene */
  24178. set: function (callback) {
  24179. if (this._onBeforeRenderObserver) {
  24180. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24181. }
  24182. if (callback) {
  24183. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24184. }
  24185. },
  24186. enumerable: true,
  24187. configurable: true
  24188. });
  24189. Object.defineProperty(Scene.prototype, "afterRender", {
  24190. /** Sets a function to be executed after rendering this scene */
  24191. set: function (callback) {
  24192. if (this._onAfterRenderObserver) {
  24193. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24194. }
  24195. if (callback) {
  24196. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24197. }
  24198. },
  24199. enumerable: true,
  24200. configurable: true
  24201. });
  24202. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24203. /** Sets a function to be executed before rendering a camera*/
  24204. set: function (callback) {
  24205. if (this._onBeforeCameraRenderObserver) {
  24206. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24207. }
  24208. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24209. },
  24210. enumerable: true,
  24211. configurable: true
  24212. });
  24213. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24214. /** Sets a function to be executed after rendering a camera*/
  24215. set: function (callback) {
  24216. if (this._onAfterCameraRenderObserver) {
  24217. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24218. }
  24219. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24220. },
  24221. enumerable: true,
  24222. configurable: true
  24223. });
  24224. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24225. /**
  24226. * Gets the gamepad manager associated with the scene
  24227. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24228. */
  24229. get: function () {
  24230. if (!this._gamepadManager) {
  24231. this._gamepadManager = new BABYLON.GamepadManager(this);
  24232. }
  24233. return this._gamepadManager;
  24234. },
  24235. enumerable: true,
  24236. configurable: true
  24237. });
  24238. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24239. /**
  24240. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24241. */
  24242. get: function () {
  24243. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24244. },
  24245. enumerable: true,
  24246. configurable: true
  24247. });
  24248. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24249. get: function () {
  24250. return this._useRightHandedSystem;
  24251. },
  24252. /**
  24253. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24254. */
  24255. set: function (value) {
  24256. if (this._useRightHandedSystem === value) {
  24257. return;
  24258. }
  24259. this._useRightHandedSystem = value;
  24260. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24261. },
  24262. enumerable: true,
  24263. configurable: true
  24264. });
  24265. /**
  24266. * Sets the step Id used by deterministic lock step
  24267. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24268. * @param newStepId defines the step Id
  24269. */
  24270. Scene.prototype.setStepId = function (newStepId) {
  24271. this._currentStepId = newStepId;
  24272. };
  24273. ;
  24274. /**
  24275. * Gets the step Id used by deterministic lock step
  24276. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24277. * @returns the step Id
  24278. */
  24279. Scene.prototype.getStepId = function () {
  24280. return this._currentStepId;
  24281. };
  24282. ;
  24283. /**
  24284. * Gets the internal step used by deterministic lock step
  24285. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24286. * @returns the internal step
  24287. */
  24288. Scene.prototype.getInternalStep = function () {
  24289. return this._currentInternalStep;
  24290. };
  24291. ;
  24292. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24293. get: function () {
  24294. return this._fogEnabled;
  24295. },
  24296. /**
  24297. * Gets or sets a boolean indicating if fog is enabled on this scene
  24298. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24299. */
  24300. set: function (value) {
  24301. if (this._fogEnabled === value) {
  24302. return;
  24303. }
  24304. this._fogEnabled = value;
  24305. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24306. },
  24307. enumerable: true,
  24308. configurable: true
  24309. });
  24310. Object.defineProperty(Scene.prototype, "fogMode", {
  24311. get: function () {
  24312. return this._fogMode;
  24313. },
  24314. /**
  24315. * Gets or sets the fog mode to use
  24316. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24317. */
  24318. set: function (value) {
  24319. if (this._fogMode === value) {
  24320. return;
  24321. }
  24322. this._fogMode = value;
  24323. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24324. },
  24325. enumerable: true,
  24326. configurable: true
  24327. });
  24328. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24329. get: function () {
  24330. return this._shadowsEnabled;
  24331. },
  24332. /**
  24333. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24334. */
  24335. set: function (value) {
  24336. if (this._shadowsEnabled === value) {
  24337. return;
  24338. }
  24339. this._shadowsEnabled = value;
  24340. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24341. },
  24342. enumerable: true,
  24343. configurable: true
  24344. });
  24345. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24346. get: function () {
  24347. return this._lightsEnabled;
  24348. },
  24349. /**
  24350. * Gets or sets a boolean indicating if lights are enabled on this scene
  24351. */
  24352. set: function (value) {
  24353. if (this._lightsEnabled === value) {
  24354. return;
  24355. }
  24356. this._lightsEnabled = value;
  24357. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24358. },
  24359. enumerable: true,
  24360. configurable: true
  24361. });
  24362. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24363. /** The default material used on meshes when no material is affected */
  24364. get: function () {
  24365. if (!this._defaultMaterial) {
  24366. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24367. }
  24368. return this._defaultMaterial;
  24369. },
  24370. /** The default material used on meshes when no material is affected */
  24371. set: function (value) {
  24372. this._defaultMaterial = value;
  24373. },
  24374. enumerable: true,
  24375. configurable: true
  24376. });
  24377. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24378. get: function () {
  24379. return this._texturesEnabled;
  24380. },
  24381. /**
  24382. * Gets or sets a boolean indicating if textures are enabled on this scene
  24383. */
  24384. set: function (value) {
  24385. if (this._texturesEnabled === value) {
  24386. return;
  24387. }
  24388. this._texturesEnabled = value;
  24389. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24390. },
  24391. enumerable: true,
  24392. configurable: true
  24393. });
  24394. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24395. get: function () {
  24396. return this._skeletonsEnabled;
  24397. },
  24398. /**
  24399. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24400. */
  24401. set: function (value) {
  24402. if (this._skeletonsEnabled === value) {
  24403. return;
  24404. }
  24405. this._skeletonsEnabled = value;
  24406. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24407. },
  24408. enumerable: true,
  24409. configurable: true
  24410. });
  24411. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24412. /**
  24413. * Gets the postprocess render pipeline manager
  24414. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24415. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24416. */
  24417. get: function () {
  24418. if (!this._postProcessRenderPipelineManager) {
  24419. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24420. }
  24421. return this._postProcessRenderPipelineManager;
  24422. },
  24423. enumerable: true,
  24424. configurable: true
  24425. });
  24426. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24427. /**
  24428. * Gets the main soundtrack associated with the scene
  24429. */
  24430. get: function () {
  24431. if (!this._mainSoundTrack) {
  24432. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24433. }
  24434. return this._mainSoundTrack;
  24435. },
  24436. enumerable: true,
  24437. configurable: true
  24438. });
  24439. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24440. /** @hidden */
  24441. get: function () {
  24442. return this._alternateRendering;
  24443. },
  24444. enumerable: true,
  24445. configurable: true
  24446. });
  24447. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24448. /**
  24449. * Gets the list of frustum planes (built from the active camera)
  24450. */
  24451. get: function () {
  24452. return this._frustumPlanes;
  24453. },
  24454. enumerable: true,
  24455. configurable: true
  24456. });
  24457. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24458. /**
  24459. * Gets the current geometry buffer associated to the scene.
  24460. */
  24461. get: function () {
  24462. return this._geometryBufferRenderer;
  24463. },
  24464. /**
  24465. * Sets the current geometry buffer for the scene.
  24466. */
  24467. set: function (geometryBufferRenderer) {
  24468. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24469. this._geometryBufferRenderer = geometryBufferRenderer;
  24470. }
  24471. },
  24472. enumerable: true,
  24473. configurable: true
  24474. });
  24475. Object.defineProperty(Scene.prototype, "debugLayer", {
  24476. /**
  24477. * Gets the debug layer associated with the scene
  24478. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24479. */
  24480. get: function () {
  24481. if (!this._debugLayer) {
  24482. this._debugLayer = new BABYLON.DebugLayer(this);
  24483. }
  24484. return this._debugLayer;
  24485. },
  24486. enumerable: true,
  24487. configurable: true
  24488. });
  24489. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24490. /**
  24491. * Gets a boolean indicating if collisions are processed on a web worker
  24492. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24493. */
  24494. get: function () {
  24495. return this._workerCollisions;
  24496. },
  24497. set: function (enabled) {
  24498. if (!BABYLON.CollisionCoordinatorLegacy) {
  24499. return;
  24500. }
  24501. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24502. this._workerCollisions = enabled;
  24503. if (this.collisionCoordinator) {
  24504. this.collisionCoordinator.destroy();
  24505. }
  24506. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24507. this.collisionCoordinator.init(this);
  24508. },
  24509. enumerable: true,
  24510. configurable: true
  24511. });
  24512. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24513. /**
  24514. * Gets the octree used to boost mesh selection (picking)
  24515. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24516. */
  24517. get: function () {
  24518. return this._selectionOctree;
  24519. },
  24520. enumerable: true,
  24521. configurable: true
  24522. });
  24523. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24524. /**
  24525. * Gets the mesh that is currently under the pointer
  24526. */
  24527. get: function () {
  24528. return this._pointerOverMesh;
  24529. },
  24530. enumerable: true,
  24531. configurable: true
  24532. });
  24533. Object.defineProperty(Scene.prototype, "pointerX", {
  24534. /**
  24535. * Gets the current on-screen X position of the pointer
  24536. */
  24537. get: function () {
  24538. return this._pointerX;
  24539. },
  24540. enumerable: true,
  24541. configurable: true
  24542. });
  24543. Object.defineProperty(Scene.prototype, "pointerY", {
  24544. /**
  24545. * Gets the current on-screen Y position of the pointer
  24546. */
  24547. get: function () {
  24548. return this._pointerY;
  24549. },
  24550. enumerable: true,
  24551. configurable: true
  24552. });
  24553. /**
  24554. * Gets the cached material (ie. the latest rendered one)
  24555. * @returns the cached material
  24556. */
  24557. Scene.prototype.getCachedMaterial = function () {
  24558. return this._cachedMaterial;
  24559. };
  24560. /**
  24561. * Gets the cached effect (ie. the latest rendered one)
  24562. * @returns the cached effect
  24563. */
  24564. Scene.prototype.getCachedEffect = function () {
  24565. return this._cachedEffect;
  24566. };
  24567. /**
  24568. * Gets the cached visibility state (ie. the latest rendered one)
  24569. * @returns the cached visibility state
  24570. */
  24571. Scene.prototype.getCachedVisibility = function () {
  24572. return this._cachedVisibility;
  24573. };
  24574. /**
  24575. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24576. * @param material defines the current material
  24577. * @param effect defines the current effect
  24578. * @param visibility defines the current visibility state
  24579. * @returns true if one parameter is not cached
  24580. */
  24581. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24582. if (visibility === void 0) { visibility = 1; }
  24583. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24584. };
  24585. /**
  24586. * Gets the bounding box renderer associated with the scene
  24587. * @returns a BoundingBoxRenderer
  24588. */
  24589. Scene.prototype.getBoundingBoxRenderer = function () {
  24590. if (!this._boundingBoxRenderer) {
  24591. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24592. }
  24593. return this._boundingBoxRenderer;
  24594. };
  24595. /**
  24596. * Gets the outline renderer associated with the scene
  24597. * @returns a OutlineRenderer
  24598. */
  24599. Scene.prototype.getOutlineRenderer = function () {
  24600. return this._outlineRenderer;
  24601. };
  24602. /**
  24603. * Gets the engine associated with the scene
  24604. * @returns an Engine
  24605. */
  24606. Scene.prototype.getEngine = function () {
  24607. return this._engine;
  24608. };
  24609. /**
  24610. * Gets the total number of vertices rendered per frame
  24611. * @returns the total number of vertices rendered per frame
  24612. */
  24613. Scene.prototype.getTotalVertices = function () {
  24614. return this._totalVertices.current;
  24615. };
  24616. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24617. /**
  24618. * Gets the performance counter for total vertices
  24619. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24620. */
  24621. get: function () {
  24622. return this._totalVertices;
  24623. },
  24624. enumerable: true,
  24625. configurable: true
  24626. });
  24627. /**
  24628. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24629. * @returns the total number of active indices rendered per frame
  24630. */
  24631. Scene.prototype.getActiveIndices = function () {
  24632. return this._activeIndices.current;
  24633. };
  24634. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24635. /**
  24636. * Gets the performance counter for active indices
  24637. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24638. */
  24639. get: function () {
  24640. return this._activeIndices;
  24641. },
  24642. enumerable: true,
  24643. configurable: true
  24644. });
  24645. /**
  24646. * Gets the total number of active particles rendered per frame
  24647. * @returns the total number of active particles rendered per frame
  24648. */
  24649. Scene.prototype.getActiveParticles = function () {
  24650. return this._activeParticles.current;
  24651. };
  24652. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24653. /**
  24654. * Gets the performance counter for active particles
  24655. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24656. */
  24657. get: function () {
  24658. return this._activeParticles;
  24659. },
  24660. enumerable: true,
  24661. configurable: true
  24662. });
  24663. /**
  24664. * Gets the total number of active bones rendered per frame
  24665. * @returns the total number of active bones rendered per frame
  24666. */
  24667. Scene.prototype.getActiveBones = function () {
  24668. return this._activeBones.current;
  24669. };
  24670. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24671. /**
  24672. * Gets the performance counter for active bones
  24673. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24674. */
  24675. get: function () {
  24676. return this._activeBones;
  24677. },
  24678. enumerable: true,
  24679. configurable: true
  24680. });
  24681. /** @hidden */
  24682. Scene.prototype.getInterFramePerfCounter = function () {
  24683. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24684. return 0;
  24685. };
  24686. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24687. /** @hidden */
  24688. get: function () {
  24689. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24690. return null;
  24691. },
  24692. enumerable: true,
  24693. configurable: true
  24694. });
  24695. /** @hidden */
  24696. Scene.prototype.getLastFrameDuration = function () {
  24697. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24698. return 0;
  24699. };
  24700. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24701. /** @hidden */
  24702. get: function () {
  24703. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24704. return null;
  24705. },
  24706. enumerable: true,
  24707. configurable: true
  24708. });
  24709. /** @hidden */
  24710. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24711. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24712. return 0;
  24713. };
  24714. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24715. /** @hidden */
  24716. get: function () {
  24717. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24718. return null;
  24719. },
  24720. enumerable: true,
  24721. configurable: true
  24722. });
  24723. /**
  24724. * Gets the array of active meshes
  24725. * @returns an array of AbstractMesh
  24726. */
  24727. Scene.prototype.getActiveMeshes = function () {
  24728. return this._activeMeshes;
  24729. };
  24730. /** @hidden */
  24731. Scene.prototype.getRenderTargetsDuration = function () {
  24732. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24733. return 0;
  24734. };
  24735. /** @hidden */
  24736. Scene.prototype.getRenderDuration = function () {
  24737. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24738. return 0;
  24739. };
  24740. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24741. /** @hidden */
  24742. get: function () {
  24743. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24744. return null;
  24745. },
  24746. enumerable: true,
  24747. configurable: true
  24748. });
  24749. /** @hidden */
  24750. Scene.prototype.getParticlesDuration = function () {
  24751. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24752. return 0;
  24753. };
  24754. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24755. /** @hidden */
  24756. get: function () {
  24757. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24758. return null;
  24759. },
  24760. enumerable: true,
  24761. configurable: true
  24762. });
  24763. /** @hidden */
  24764. Scene.prototype.getSpritesDuration = function () {
  24765. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24766. return 0;
  24767. };
  24768. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24769. /** @hidden */
  24770. get: function () {
  24771. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24772. return null;
  24773. },
  24774. enumerable: true,
  24775. configurable: true
  24776. });
  24777. /**
  24778. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24779. * @returns a number
  24780. */
  24781. Scene.prototype.getAnimationRatio = function () {
  24782. return this._animationRatio;
  24783. };
  24784. /**
  24785. * Gets an unique Id for the current frame
  24786. * @returns a number
  24787. */
  24788. Scene.prototype.getRenderId = function () {
  24789. return this._renderId;
  24790. };
  24791. /** Call this function if you want to manually increment the render Id*/
  24792. Scene.prototype.incrementRenderId = function () {
  24793. this._renderId++;
  24794. };
  24795. Scene.prototype._updatePointerPosition = function (evt) {
  24796. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24797. if (!canvasRect) {
  24798. return;
  24799. }
  24800. this._pointerX = evt.clientX - canvasRect.left;
  24801. this._pointerY = evt.clientY - canvasRect.top;
  24802. this._unTranslatedPointerX = this._pointerX;
  24803. this._unTranslatedPointerY = this._pointerY;
  24804. };
  24805. Scene.prototype._createUbo = function () {
  24806. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24807. this._sceneUbo.addUniform("viewProjection", 16);
  24808. this._sceneUbo.addUniform("view", 16);
  24809. };
  24810. Scene.prototype._createAlternateUbo = function () {
  24811. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24812. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24813. this._alternateSceneUbo.addUniform("view", 16);
  24814. };
  24815. // Pointers handling
  24816. /**
  24817. * Use this method to simulate a pointer move on a mesh
  24818. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24819. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24820. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24821. * @returns the current scene
  24822. */
  24823. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24824. var evt = new PointerEvent("pointermove", pointerEventInit);
  24825. return this._processPointerMove(pickResult, evt);
  24826. };
  24827. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24828. var canvas = this._engine.getRenderingCanvas();
  24829. if (!canvas) {
  24830. return this;
  24831. }
  24832. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24833. this.setPointerOverSprite(null);
  24834. this.setPointerOverMesh(pickResult.pickedMesh);
  24835. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24836. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24837. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24838. }
  24839. else {
  24840. canvas.style.cursor = this.hoverCursor;
  24841. }
  24842. }
  24843. else {
  24844. canvas.style.cursor = this.defaultCursor;
  24845. }
  24846. }
  24847. else {
  24848. this.setPointerOverMesh(null);
  24849. // Sprites
  24850. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24851. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24852. this.setPointerOverSprite(pickResult.pickedSprite);
  24853. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24854. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24855. }
  24856. else {
  24857. canvas.style.cursor = this.hoverCursor;
  24858. }
  24859. }
  24860. else {
  24861. this.setPointerOverSprite(null);
  24862. // Restore pointer
  24863. canvas.style.cursor = this.defaultCursor;
  24864. }
  24865. }
  24866. if (pickResult) {
  24867. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24868. if (this.onPointerMove) {
  24869. this.onPointerMove(evt, pickResult, type);
  24870. }
  24871. if (this.onPointerObservable.hasObservers()) {
  24872. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24873. this.onPointerObservable.notifyObservers(pi, type);
  24874. }
  24875. }
  24876. return this;
  24877. };
  24878. /**
  24879. * Use this method to simulate a pointer down on a mesh
  24880. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24881. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24882. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24883. * @returns the current scene
  24884. */
  24885. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24886. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24887. return this._processPointerDown(pickResult, evt);
  24888. };
  24889. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24890. var _this = this;
  24891. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24892. this._pickedDownMesh = pickResult.pickedMesh;
  24893. var actionManager = pickResult.pickedMesh.actionManager;
  24894. if (actionManager) {
  24895. if (actionManager.hasPickTriggers) {
  24896. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24897. switch (evt.button) {
  24898. case 0:
  24899. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24900. break;
  24901. case 1:
  24902. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24903. break;
  24904. case 2:
  24905. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24906. break;
  24907. }
  24908. }
  24909. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24910. window.setTimeout(function () {
  24911. 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);
  24912. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24913. if (_this._totalPointersPressed !== 0 &&
  24914. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24915. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24916. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24917. _this._startingPointerTime = 0;
  24918. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24919. }
  24920. }
  24921. }, Scene.LongPressDelay);
  24922. }
  24923. }
  24924. }
  24925. if (pickResult) {
  24926. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24927. if (this.onPointerDown) {
  24928. this.onPointerDown(evt, pickResult, type);
  24929. }
  24930. if (this.onPointerObservable.hasObservers()) {
  24931. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24932. this.onPointerObservable.notifyObservers(pi, type);
  24933. }
  24934. }
  24935. return this;
  24936. };
  24937. /**
  24938. * Use this method to simulate a pointer up on a mesh
  24939. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24940. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24941. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24942. * @returns the current scene
  24943. */
  24944. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24945. var evt = new PointerEvent("pointerup", pointerEventInit);
  24946. var clickInfo = new ClickInfo();
  24947. clickInfo.singleClick = true;
  24948. clickInfo.ignore = true;
  24949. return this._processPointerUp(pickResult, evt, clickInfo);
  24950. };
  24951. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24952. if (pickResult && pickResult && pickResult.pickedMesh) {
  24953. this._pickedUpMesh = pickResult.pickedMesh;
  24954. if (this._pickedDownMesh === this._pickedUpMesh) {
  24955. if (this.onPointerPick) {
  24956. this.onPointerPick(evt, pickResult);
  24957. }
  24958. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24959. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24960. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24961. this.onPointerObservable.notifyObservers(pi, type_1);
  24962. }
  24963. }
  24964. if (pickResult.pickedMesh.actionManager) {
  24965. if (clickInfo.ignore) {
  24966. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24967. }
  24968. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24969. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24970. }
  24971. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24972. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24973. }
  24974. }
  24975. }
  24976. if (this._pickedDownMesh &&
  24977. this._pickedDownMesh.actionManager &&
  24978. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24979. this._pickedDownMesh !== this._pickedUpMesh) {
  24980. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24981. }
  24982. var type = BABYLON.PointerEventTypes.POINTERUP;
  24983. if (this.onPointerObservable.hasObservers()) {
  24984. if (!clickInfo.ignore) {
  24985. if (!clickInfo.hasSwiped) {
  24986. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24987. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24988. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24989. this.onPointerObservable.notifyObservers(pi, type_2);
  24990. }
  24991. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24992. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24993. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24994. this.onPointerObservable.notifyObservers(pi, type_3);
  24995. }
  24996. }
  24997. }
  24998. else {
  24999. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25000. this.onPointerObservable.notifyObservers(pi, type);
  25001. }
  25002. }
  25003. if (this.onPointerUp) {
  25004. this.onPointerUp(evt, pickResult, type);
  25005. }
  25006. return this;
  25007. };
  25008. /**
  25009. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25010. * @param attachUp defines if you want to attach events to pointerup
  25011. * @param attachDown defines if you want to attach events to pointerdown
  25012. * @param attachMove defines if you want to attach events to pointermove
  25013. */
  25014. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25015. var _this = this;
  25016. if (attachUp === void 0) { attachUp = true; }
  25017. if (attachDown === void 0) { attachDown = true; }
  25018. if (attachMove === void 0) { attachMove = true; }
  25019. this._initActionManager = function (act, clickInfo) {
  25020. if (!_this._meshPickProceed) {
  25021. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25022. _this._currentPickResult = pickResult;
  25023. if (pickResult) {
  25024. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25025. }
  25026. _this._meshPickProceed = true;
  25027. }
  25028. return act;
  25029. };
  25030. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25031. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25032. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25033. btn !== _this._previousButtonPressed) {
  25034. _this._doubleClickOccured = false;
  25035. clickInfo.singleClick = true;
  25036. clickInfo.ignore = false;
  25037. cb(clickInfo, _this._currentPickResult);
  25038. }
  25039. };
  25040. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25041. var clickInfo = new ClickInfo();
  25042. _this._currentPickResult = null;
  25043. var act = null;
  25044. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25045. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25046. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25047. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25048. act = _this._initActionManager(act, clickInfo);
  25049. if (act)
  25050. checkPicking = act.hasPickTriggers;
  25051. }
  25052. if (checkPicking) {
  25053. var btn = evt.button;
  25054. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25055. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25056. if (!clickInfo.hasSwiped) {
  25057. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25058. if (!checkSingleClickImmediately) {
  25059. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25060. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25061. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25062. act = _this._initActionManager(act, clickInfo);
  25063. if (act)
  25064. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25065. }
  25066. }
  25067. if (checkSingleClickImmediately) {
  25068. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25069. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25070. btn !== _this._previousButtonPressed) {
  25071. clickInfo.singleClick = true;
  25072. cb(clickInfo, _this._currentPickResult);
  25073. }
  25074. }
  25075. // at least one double click is required to be check and exclusive double click is enabled
  25076. else {
  25077. // wait that no double click has been raised during the double click delay
  25078. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25079. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25080. }
  25081. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25082. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25083. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25084. act = _this._initActionManager(act, clickInfo);
  25085. if (act)
  25086. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25087. }
  25088. if (checkDoubleClick) {
  25089. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25090. if (btn === _this._previousButtonPressed &&
  25091. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25092. !_this._doubleClickOccured) {
  25093. // pointer has not moved for 2 clicks, it's a double click
  25094. if (!clickInfo.hasSwiped &&
  25095. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25096. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25097. _this._previousStartingPointerTime = 0;
  25098. _this._doubleClickOccured = true;
  25099. clickInfo.doubleClick = true;
  25100. clickInfo.ignore = false;
  25101. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25102. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25103. }
  25104. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25105. cb(clickInfo, _this._currentPickResult);
  25106. }
  25107. // if the two successive clicks are too far, it's just two simple clicks
  25108. else {
  25109. _this._doubleClickOccured = false;
  25110. _this._previousStartingPointerTime = _this._startingPointerTime;
  25111. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25112. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25113. _this._previousButtonPressed = btn;
  25114. if (Scene.ExclusiveDoubleClickMode) {
  25115. if (_this._previousDelayedSimpleClickTimeout) {
  25116. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25117. }
  25118. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25119. cb(clickInfo, _this._previousPickResult);
  25120. }
  25121. else {
  25122. cb(clickInfo, _this._currentPickResult);
  25123. }
  25124. }
  25125. }
  25126. // just the first click of the double has been raised
  25127. else {
  25128. _this._doubleClickOccured = false;
  25129. _this._previousStartingPointerTime = _this._startingPointerTime;
  25130. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25131. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25132. _this._previousButtonPressed = btn;
  25133. }
  25134. }
  25135. }
  25136. }
  25137. clickInfo.ignore = true;
  25138. cb(clickInfo, _this._currentPickResult);
  25139. };
  25140. this._spritePredicate = function (sprite) {
  25141. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25142. };
  25143. this._onPointerMove = function (evt) {
  25144. _this._updatePointerPosition(evt);
  25145. // PreObservable support
  25146. if (_this.onPrePointerObservable.hasObservers()) {
  25147. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25148. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25149. _this.onPrePointerObservable.notifyObservers(pi, type);
  25150. if (pi.skipOnPointerObservable) {
  25151. return;
  25152. }
  25153. }
  25154. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25155. return;
  25156. }
  25157. if (!_this.pointerMovePredicate) {
  25158. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25159. }
  25160. // Meshes
  25161. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25162. _this._processPointerMove(pickResult, evt);
  25163. };
  25164. this._onPointerDown = function (evt) {
  25165. _this._totalPointersPressed++;
  25166. _this._pickedDownMesh = null;
  25167. _this._meshPickProceed = false;
  25168. _this._updatePointerPosition(evt);
  25169. if (_this.preventDefaultOnPointerDown && canvas) {
  25170. evt.preventDefault();
  25171. canvas.focus();
  25172. }
  25173. // PreObservable support
  25174. if (_this.onPrePointerObservable.hasObservers()) {
  25175. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25176. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25177. _this.onPrePointerObservable.notifyObservers(pi, type);
  25178. if (pi.skipOnPointerObservable) {
  25179. return;
  25180. }
  25181. }
  25182. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25183. return;
  25184. }
  25185. _this._startingPointerPosition.x = _this._pointerX;
  25186. _this._startingPointerPosition.y = _this._pointerY;
  25187. _this._startingPointerTime = Date.now();
  25188. if (!_this.pointerDownPredicate) {
  25189. _this.pointerDownPredicate = function (mesh) {
  25190. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25191. };
  25192. }
  25193. // Meshes
  25194. _this._pickedDownMesh = null;
  25195. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25196. _this._processPointerDown(pickResult, evt);
  25197. // Sprites
  25198. _this._pickedDownSprite = null;
  25199. if (_this.spriteManagers.length > 0) {
  25200. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25201. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25202. if (pickResult.pickedSprite.actionManager) {
  25203. _this._pickedDownSprite = pickResult.pickedSprite;
  25204. switch (evt.button) {
  25205. case 0:
  25206. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25207. break;
  25208. case 1:
  25209. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25210. break;
  25211. case 2:
  25212. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25213. break;
  25214. }
  25215. if (pickResult.pickedSprite.actionManager) {
  25216. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25217. }
  25218. }
  25219. }
  25220. }
  25221. };
  25222. this._onPointerUp = function (evt) {
  25223. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25224. return; // So we need to test it the pointer down was pressed before.
  25225. }
  25226. _this._totalPointersPressed--;
  25227. _this._pickedUpMesh = null;
  25228. _this._meshPickProceed = false;
  25229. _this._updatePointerPosition(evt);
  25230. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25231. // PreObservable support
  25232. if (_this.onPrePointerObservable.hasObservers()) {
  25233. if (!clickInfo.ignore) {
  25234. if (!clickInfo.hasSwiped) {
  25235. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25236. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25237. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25238. _this.onPrePointerObservable.notifyObservers(pi, type);
  25239. if (pi.skipOnPointerObservable) {
  25240. return;
  25241. }
  25242. }
  25243. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25244. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25245. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25246. _this.onPrePointerObservable.notifyObservers(pi, type);
  25247. if (pi.skipOnPointerObservable) {
  25248. return;
  25249. }
  25250. }
  25251. }
  25252. }
  25253. else {
  25254. var type = BABYLON.PointerEventTypes.POINTERUP;
  25255. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25256. _this.onPrePointerObservable.notifyObservers(pi, type);
  25257. if (pi.skipOnPointerObservable) {
  25258. return;
  25259. }
  25260. }
  25261. }
  25262. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25263. return;
  25264. }
  25265. if (!_this.pointerUpPredicate) {
  25266. _this.pointerUpPredicate = function (mesh) {
  25267. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25268. };
  25269. }
  25270. // Meshes
  25271. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25272. _this._initActionManager(null, clickInfo);
  25273. }
  25274. if (!pickResult) {
  25275. pickResult = _this._currentPickResult;
  25276. }
  25277. _this._processPointerUp(pickResult, evt, clickInfo);
  25278. // Sprites
  25279. if (!clickInfo.ignore) {
  25280. if (_this.spriteManagers.length > 0) {
  25281. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25282. if (spritePickResult) {
  25283. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25284. if (spritePickResult.pickedSprite.actionManager) {
  25285. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25286. if (spritePickResult.pickedSprite.actionManager) {
  25287. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25288. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25289. }
  25290. }
  25291. }
  25292. }
  25293. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25294. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25295. }
  25296. }
  25297. }
  25298. }
  25299. _this._previousPickResult = _this._currentPickResult;
  25300. });
  25301. };
  25302. this._onKeyDown = function (evt) {
  25303. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25304. if (_this.onPreKeyboardObservable.hasObservers()) {
  25305. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25306. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25307. if (pi.skipOnPointerObservable) {
  25308. return;
  25309. }
  25310. }
  25311. if (_this.onKeyboardObservable.hasObservers()) {
  25312. var pi = new BABYLON.KeyboardInfo(type, evt);
  25313. _this.onKeyboardObservable.notifyObservers(pi, type);
  25314. }
  25315. if (_this.actionManager) {
  25316. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25317. }
  25318. };
  25319. this._onKeyUp = function (evt) {
  25320. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25321. if (_this.onPreKeyboardObservable.hasObservers()) {
  25322. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25323. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25324. if (pi.skipOnPointerObservable) {
  25325. return;
  25326. }
  25327. }
  25328. if (_this.onKeyboardObservable.hasObservers()) {
  25329. var pi = new BABYLON.KeyboardInfo(type, evt);
  25330. _this.onKeyboardObservable.notifyObservers(pi, type);
  25331. }
  25332. if (_this.actionManager) {
  25333. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25334. }
  25335. };
  25336. var engine = this.getEngine();
  25337. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25338. if (!canvas) {
  25339. return;
  25340. }
  25341. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25342. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25343. });
  25344. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25345. if (!canvas) {
  25346. return;
  25347. }
  25348. canvas.removeEventListener("keydown", _this._onKeyDown);
  25349. canvas.removeEventListener("keyup", _this._onKeyUp);
  25350. });
  25351. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25352. var canvas = this._engine.getRenderingCanvas();
  25353. if (!canvas) {
  25354. return;
  25355. }
  25356. if (attachMove) {
  25357. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25358. // Wheel
  25359. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25360. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25361. }
  25362. if (attachDown) {
  25363. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25364. }
  25365. if (attachUp) {
  25366. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25367. }
  25368. canvas.tabIndex = 1;
  25369. };
  25370. /** Detaches all event handlers*/
  25371. Scene.prototype.detachControl = function () {
  25372. var engine = this.getEngine();
  25373. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25374. var canvas = engine.getRenderingCanvas();
  25375. if (!canvas) {
  25376. return;
  25377. }
  25378. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25379. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25380. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25381. if (this._onCanvasBlurObserver) {
  25382. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25383. }
  25384. if (this._onCanvasFocusObserver) {
  25385. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25386. }
  25387. // Wheel
  25388. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25389. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25390. // Keyboard
  25391. canvas.removeEventListener("keydown", this._onKeyDown);
  25392. canvas.removeEventListener("keyup", this._onKeyUp);
  25393. // Observables
  25394. this.onKeyboardObservable.clear();
  25395. this.onPreKeyboardObservable.clear();
  25396. this.onPointerObservable.clear();
  25397. this.onPrePointerObservable.clear();
  25398. };
  25399. /**
  25400. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25401. * Delay loaded resources are not taking in account
  25402. * @return true if all required resources are ready
  25403. */
  25404. Scene.prototype.isReady = function () {
  25405. if (this._isDisposed) {
  25406. return false;
  25407. }
  25408. if (this._pendingData.length > 0) {
  25409. return false;
  25410. }
  25411. var index;
  25412. var engine = this.getEngine();
  25413. // Geometries
  25414. for (index = 0; index < this._geometries.length; index++) {
  25415. var geometry = this._geometries[index];
  25416. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25417. return false;
  25418. }
  25419. }
  25420. // Meshes
  25421. for (index = 0; index < this.meshes.length; index++) {
  25422. var mesh = this.meshes[index];
  25423. if (!mesh.isEnabled()) {
  25424. continue;
  25425. }
  25426. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25427. continue;
  25428. }
  25429. if (!mesh.isReady(true)) {
  25430. return false;
  25431. }
  25432. // Effect layers
  25433. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25434. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25435. var layer = _a[_i];
  25436. if (!layer.hasMesh(mesh)) {
  25437. continue;
  25438. }
  25439. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25440. var subMesh = _c[_b];
  25441. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25442. return false;
  25443. }
  25444. }
  25445. }
  25446. }
  25447. // Post-processes
  25448. if (this.activeCameras && this.activeCameras.length > 0) {
  25449. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25450. var camera = _e[_d];
  25451. if (!camera.isReady(true)) {
  25452. return false;
  25453. }
  25454. }
  25455. }
  25456. else if (this.activeCamera) {
  25457. if (!this.activeCamera.isReady(true)) {
  25458. return false;
  25459. }
  25460. }
  25461. // Particles
  25462. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25463. var particleSystem = _g[_f];
  25464. if (!particleSystem.isReady()) {
  25465. return false;
  25466. }
  25467. }
  25468. return true;
  25469. };
  25470. /** Resets all cached information relative to material (including effect and visibility) */
  25471. Scene.prototype.resetCachedMaterial = function () {
  25472. this._cachedMaterial = null;
  25473. this._cachedEffect = null;
  25474. this._cachedVisibility = null;
  25475. };
  25476. /**
  25477. * Registers a function to be called before every frame render
  25478. * @param func defines the function to register
  25479. */
  25480. Scene.prototype.registerBeforeRender = function (func) {
  25481. this.onBeforeRenderObservable.add(func);
  25482. };
  25483. /**
  25484. * Unregisters a function called before every frame render
  25485. * @param func defines the function to unregister
  25486. */
  25487. Scene.prototype.unregisterBeforeRender = function (func) {
  25488. this.onBeforeRenderObservable.removeCallback(func);
  25489. };
  25490. /**
  25491. * Registers a function to be called after every frame render
  25492. * @param func defines the function to register
  25493. */
  25494. Scene.prototype.registerAfterRender = function (func) {
  25495. this.onAfterRenderObservable.add(func);
  25496. };
  25497. /**
  25498. * Unregisters a function called after every frame render
  25499. * @param func defines the function to unregister
  25500. */
  25501. Scene.prototype.unregisterAfterRender = function (func) {
  25502. this.onAfterRenderObservable.removeCallback(func);
  25503. };
  25504. Scene.prototype._executeOnceBeforeRender = function (func) {
  25505. var _this = this;
  25506. var execFunc = function () {
  25507. func();
  25508. setTimeout(function () {
  25509. _this.unregisterBeforeRender(execFunc);
  25510. });
  25511. };
  25512. this.registerBeforeRender(execFunc);
  25513. };
  25514. /**
  25515. * The provided function will run before render once and will be disposed afterwards.
  25516. * A timeout delay can be provided so that the function will be executed in N ms.
  25517. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25518. * @param func The function to be executed.
  25519. * @param timeout optional delay in ms
  25520. */
  25521. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25522. var _this = this;
  25523. if (timeout !== undefined) {
  25524. setTimeout(function () {
  25525. _this._executeOnceBeforeRender(func);
  25526. }, timeout);
  25527. }
  25528. else {
  25529. this._executeOnceBeforeRender(func);
  25530. }
  25531. };
  25532. /** @hidden */
  25533. Scene.prototype._addPendingData = function (data) {
  25534. this._pendingData.push(data);
  25535. };
  25536. /** @hidden */
  25537. Scene.prototype._removePendingData = function (data) {
  25538. var wasLoading = this.isLoading;
  25539. var index = this._pendingData.indexOf(data);
  25540. if (index !== -1) {
  25541. this._pendingData.splice(index, 1);
  25542. }
  25543. if (wasLoading && !this.isLoading) {
  25544. this.onDataLoadedObservable.notifyObservers(this);
  25545. }
  25546. };
  25547. /**
  25548. * Returns the number of items waiting to be loaded
  25549. * @returns the number of items waiting to be loaded
  25550. */
  25551. Scene.prototype.getWaitingItemsCount = function () {
  25552. return this._pendingData.length;
  25553. };
  25554. Object.defineProperty(Scene.prototype, "isLoading", {
  25555. /**
  25556. * Returns a boolean indicating if the scene is still loading data
  25557. */
  25558. get: function () {
  25559. return this._pendingData.length > 0;
  25560. },
  25561. enumerable: true,
  25562. configurable: true
  25563. });
  25564. /**
  25565. * Registers a function to be executed when the scene is ready
  25566. * @param {Function} func - the function to be executed
  25567. */
  25568. Scene.prototype.executeWhenReady = function (func) {
  25569. var _this = this;
  25570. this.onReadyObservable.add(func);
  25571. if (this._executeWhenReadyTimeoutId !== -1) {
  25572. return;
  25573. }
  25574. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25575. _this._checkIsReady();
  25576. }, 150);
  25577. };
  25578. /**
  25579. * Returns a promise that resolves when the scene is ready
  25580. * @returns A promise that resolves when the scene is ready
  25581. */
  25582. Scene.prototype.whenReadyAsync = function () {
  25583. var _this = this;
  25584. return new Promise(function (resolve) {
  25585. _this.executeWhenReady(function () {
  25586. resolve();
  25587. });
  25588. });
  25589. };
  25590. /** @hidden */
  25591. Scene.prototype._checkIsReady = function () {
  25592. var _this = this;
  25593. if (this.isReady()) {
  25594. this.onReadyObservable.notifyObservers(this);
  25595. this.onReadyObservable.clear();
  25596. this._executeWhenReadyTimeoutId = -1;
  25597. return;
  25598. }
  25599. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25600. _this._checkIsReady();
  25601. }, 150);
  25602. };
  25603. // Animations
  25604. /**
  25605. * Will start the animation sequence of a given target
  25606. * @param target defines the target
  25607. * @param from defines from which frame should animation start
  25608. * @param to defines until which frame should animation run.
  25609. * @param weight defines the weight to apply to the animation (1.0 by default)
  25610. * @param loop defines if the animation loops
  25611. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25612. * @param onAnimationEnd defines the function to be executed when the animation ends
  25613. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25614. * @returns the animatable object created for this animation
  25615. */
  25616. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25617. if (weight === void 0) { weight = 1.0; }
  25618. if (speedRatio === void 0) { speedRatio = 1.0; }
  25619. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25620. returnedAnimatable.weight = weight;
  25621. return returnedAnimatable;
  25622. };
  25623. /**
  25624. * Will start the animation sequence of a given target
  25625. * @param target defines the target
  25626. * @param from defines from which frame should animation start
  25627. * @param to defines until which frame should animation run.
  25628. * @param loop defines if the animation loops
  25629. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25630. * @param onAnimationEnd defines the function to be executed when the animation ends
  25631. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25632. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25633. * @returns the animatable object created for this animation
  25634. */
  25635. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25636. if (speedRatio === void 0) { speedRatio = 1.0; }
  25637. if (stopCurrent === void 0) { stopCurrent = true; }
  25638. if (from > to && speedRatio > 0) {
  25639. speedRatio *= -1;
  25640. }
  25641. if (stopCurrent) {
  25642. this.stopAnimation(target);
  25643. }
  25644. if (!animatable) {
  25645. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25646. }
  25647. // Local animations
  25648. if (target.animations) {
  25649. animatable.appendAnimations(target, target.animations);
  25650. }
  25651. // Children animations
  25652. if (target.getAnimatables) {
  25653. var animatables = target.getAnimatables();
  25654. for (var index = 0; index < animatables.length; index++) {
  25655. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25656. }
  25657. }
  25658. animatable.reset();
  25659. return animatable;
  25660. };
  25661. /**
  25662. * Begin a new animation on a given node
  25663. * @param target defines the target where the animation will take place
  25664. * @param animations defines the list of animations to start
  25665. * @param from defines the initial value
  25666. * @param to defines the final value
  25667. * @param loop defines if you want animation to loop (off by default)
  25668. * @param speedRatio defines the speed ratio to apply to all animations
  25669. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25670. * @returns the list of created animatables
  25671. */
  25672. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25673. if (speedRatio === undefined) {
  25674. speedRatio = 1.0;
  25675. }
  25676. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25677. return animatable;
  25678. };
  25679. /**
  25680. * Begin a new animation on a given node and its hierarchy
  25681. * @param target defines the root node where the animation will take place
  25682. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  25683. * @param animations defines the list of animations to start
  25684. * @param from defines the initial value
  25685. * @param to defines the final value
  25686. * @param loop defines if you want animation to loop (off by default)
  25687. * @param speedRatio defines the speed ratio to apply to all animations
  25688. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25689. * @returns the list of animatables created for all nodes
  25690. */
  25691. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25692. var children = target.getDescendants(directDescendantsOnly);
  25693. var result = [];
  25694. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25695. var child = children_1[_i];
  25696. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25697. }
  25698. return result;
  25699. };
  25700. /**
  25701. * Gets the animatable associated with a specific target
  25702. * @param target defines the target of the animatable
  25703. * @returns the required animatable if found
  25704. */
  25705. Scene.prototype.getAnimatableByTarget = function (target) {
  25706. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25707. if (this._activeAnimatables[index].target === target) {
  25708. return this._activeAnimatables[index];
  25709. }
  25710. }
  25711. return null;
  25712. };
  25713. /**
  25714. * Gets all animatables associated with a given target
  25715. * @param target defines the target to look animatables for
  25716. * @returns an array of Animatables
  25717. */
  25718. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25719. var result = [];
  25720. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25721. if (this._activeAnimatables[index].target === target) {
  25722. result.push(this._activeAnimatables[index]);
  25723. }
  25724. }
  25725. return result;
  25726. };
  25727. Object.defineProperty(Scene.prototype, "animatables", {
  25728. /**
  25729. * Gets all animatable attached to the scene
  25730. */
  25731. get: function () {
  25732. return this._activeAnimatables;
  25733. },
  25734. enumerable: true,
  25735. configurable: true
  25736. });
  25737. /**
  25738. * Will stop the animation of the given target
  25739. * @param target - the target
  25740. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25741. */
  25742. Scene.prototype.stopAnimation = function (target, animationName) {
  25743. var animatables = this.getAllAnimatablesByTarget(target);
  25744. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25745. var animatable = animatables_1[_i];
  25746. animatable.stop(animationName);
  25747. }
  25748. };
  25749. /**
  25750. * Stops and removes all animations that have been applied to the scene
  25751. */
  25752. Scene.prototype.stopAllAnimations = function () {
  25753. if (this._activeAnimatables) {
  25754. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25755. this._activeAnimatables[i].stop();
  25756. }
  25757. this._activeAnimatables = [];
  25758. }
  25759. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25760. var group = _a[_i];
  25761. group.stop();
  25762. }
  25763. };
  25764. Scene.prototype._animate = function () {
  25765. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25766. return;
  25767. }
  25768. // Getting time
  25769. var now = BABYLON.Tools.Now;
  25770. if (!this._animationTimeLast) {
  25771. if (this._pendingData.length > 0) {
  25772. return;
  25773. }
  25774. this._animationTimeLast = now;
  25775. }
  25776. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25777. this._animationTime += deltaTime;
  25778. this._animationTimeLast = now;
  25779. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25780. this._activeAnimatables[index]._animate(this._animationTime);
  25781. }
  25782. // Late animation bindings
  25783. this._processLateAnimationBindings();
  25784. };
  25785. /** @hidden */
  25786. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25787. var target = runtimeAnimation.target;
  25788. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25789. if (!target._lateAnimationHolders) {
  25790. target._lateAnimationHolders = {};
  25791. }
  25792. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25793. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25794. totalWeight: 0,
  25795. animations: []
  25796. };
  25797. }
  25798. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25799. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25800. };
  25801. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25802. var normalizer = 1.0;
  25803. var finalPosition = BABYLON.Tmp.Vector3[0];
  25804. var finalScaling = BABYLON.Tmp.Vector3[1];
  25805. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25806. var startIndex = 0;
  25807. var originalAnimation = holder.animations[0];
  25808. var scale = 1;
  25809. if (holder.totalWeight < 1.0) {
  25810. // We need to mix the original value in
  25811. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25812. scale = 1.0 - holder.totalWeight;
  25813. }
  25814. else {
  25815. startIndex = 1;
  25816. // We need to normalize the weights
  25817. normalizer = holder.totalWeight;
  25818. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25819. scale = originalAnimation.weight / normalizer;
  25820. if (scale == 1) {
  25821. return originalAnimation.currentValue;
  25822. }
  25823. }
  25824. finalScaling.scaleInPlace(scale);
  25825. finalPosition.scaleInPlace(scale);
  25826. finalQuaternion.scaleInPlace(scale);
  25827. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25828. var runtimeAnimation = holder.animations[animIndex];
  25829. var scale = runtimeAnimation.weight / normalizer;
  25830. var currentPosition = BABYLON.Tmp.Vector3[2];
  25831. var currentScaling = BABYLON.Tmp.Vector3[3];
  25832. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25833. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25834. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25835. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25836. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25837. }
  25838. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25839. return originalAnimation._workValue;
  25840. };
  25841. Scene.prototype._processLateAnimationBindings = function () {
  25842. if (!this._registeredForLateAnimationBindings.length) {
  25843. return;
  25844. }
  25845. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25846. var target = this._registeredForLateAnimationBindings.data[index];
  25847. for (var path in target._lateAnimationHolders) {
  25848. var holder = target._lateAnimationHolders[path];
  25849. var originalAnimation = holder.animations[0];
  25850. var originalValue = originalAnimation.originalValue;
  25851. var finalTarget = originalAnimation.target;
  25852. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25853. var finalValue = void 0;
  25854. if (matrixDecomposeMode) {
  25855. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25856. }
  25857. else {
  25858. var startIndex = 0;
  25859. var normalizer = 1.0;
  25860. if (holder.totalWeight < 1.0) {
  25861. // We need to mix the original value in
  25862. if (originalValue.scale) {
  25863. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25864. }
  25865. else {
  25866. finalValue = originalValue * (1.0 - holder.totalWeight);
  25867. }
  25868. }
  25869. else {
  25870. // We need to normalize the weights
  25871. normalizer = holder.totalWeight;
  25872. var scale_1 = originalAnimation.weight / normalizer;
  25873. if (scale_1 !== 1) {
  25874. if (originalAnimation.currentValue.scale) {
  25875. finalValue = originalAnimation.currentValue.scale(scale_1);
  25876. }
  25877. else {
  25878. finalValue = originalAnimation.currentValue * scale_1;
  25879. }
  25880. }
  25881. else {
  25882. finalValue = originalAnimation.currentValue;
  25883. }
  25884. startIndex = 1;
  25885. }
  25886. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25887. var runtimeAnimation = holder.animations[animIndex];
  25888. var scale = runtimeAnimation.weight / normalizer;
  25889. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25890. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25891. }
  25892. else {
  25893. finalValue += runtimeAnimation.currentValue * scale;
  25894. }
  25895. }
  25896. }
  25897. finalTarget[path] = finalValue;
  25898. }
  25899. target._lateAnimationHolders = {};
  25900. }
  25901. this._registeredForLateAnimationBindings.reset();
  25902. };
  25903. // Matrix
  25904. /** @hidden */
  25905. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25906. this._useAlternateCameraConfiguration = active;
  25907. };
  25908. /**
  25909. * Gets the current view matrix
  25910. * @returns a Matrix
  25911. */
  25912. Scene.prototype.getViewMatrix = function () {
  25913. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25914. };
  25915. /**
  25916. * Gets the current projection matrix
  25917. * @returns a Matrix
  25918. */
  25919. Scene.prototype.getProjectionMatrix = function () {
  25920. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25921. };
  25922. /**
  25923. * Gets the current transform matrix
  25924. * @returns a Matrix made of View * Projection
  25925. */
  25926. Scene.prototype.getTransformMatrix = function () {
  25927. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25928. };
  25929. /**
  25930. * Sets the current transform matrix
  25931. * @param view defines the View matrix to use
  25932. * @param projection defines the Projection matrix to use
  25933. */
  25934. Scene.prototype.setTransformMatrix = function (view, projection) {
  25935. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25936. return;
  25937. }
  25938. this._viewUpdateFlag = view.updateFlag;
  25939. this._projectionUpdateFlag = projection.updateFlag;
  25940. this._viewMatrix = view;
  25941. this._projectionMatrix = projection;
  25942. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25943. // Update frustum
  25944. if (!this._frustumPlanes) {
  25945. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25946. }
  25947. else {
  25948. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25949. }
  25950. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25951. var otherCamera = this.activeCamera._alternateCamera;
  25952. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25953. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25954. }
  25955. if (this._sceneUbo.useUbo) {
  25956. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25957. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25958. this._sceneUbo.update();
  25959. }
  25960. };
  25961. /** @hidden */
  25962. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25963. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25964. return;
  25965. }
  25966. this._alternateViewUpdateFlag = view.updateFlag;
  25967. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25968. this._alternateViewMatrix = view;
  25969. this._alternateProjectionMatrix = projection;
  25970. if (!this._alternateTransformMatrix) {
  25971. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25972. }
  25973. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25974. if (!this._alternateSceneUbo) {
  25975. this._createAlternateUbo();
  25976. }
  25977. if (this._alternateSceneUbo.useUbo) {
  25978. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25979. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25980. this._alternateSceneUbo.update();
  25981. }
  25982. };
  25983. /**
  25984. * Gets the uniform buffer used to store scene data
  25985. * @returns a UniformBuffer
  25986. */
  25987. Scene.prototype.getSceneUniformBuffer = function () {
  25988. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25989. };
  25990. /**
  25991. * Gets an unique (relatively to the current scene) Id
  25992. * @returns an unique number for the scene
  25993. */
  25994. Scene.prototype.getUniqueId = function () {
  25995. var result = Scene._uniqueIdCounter;
  25996. Scene._uniqueIdCounter++;
  25997. return result;
  25998. };
  25999. /**
  26000. * Add a mesh to the list of scene's meshes
  26001. * @param newMesh defines the mesh to add
  26002. */
  26003. Scene.prototype.addMesh = function (newMesh) {
  26004. this.meshes.push(newMesh);
  26005. //notify the collision coordinator
  26006. if (this.collisionCoordinator) {
  26007. this.collisionCoordinator.onMeshAdded(newMesh);
  26008. }
  26009. newMesh._resyncLightSources();
  26010. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26011. };
  26012. /**
  26013. * Remove a mesh for the list of scene's meshes
  26014. * @param toRemove defines the mesh to remove
  26015. * @param recursive if all child meshes should also be removed from the scene
  26016. * @returns the index where the mesh was in the mesh list
  26017. */
  26018. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26019. var _this = this;
  26020. if (recursive === void 0) { recursive = false; }
  26021. var index = this.meshes.indexOf(toRemove);
  26022. if (index !== -1) {
  26023. // Remove from the scene if mesh found
  26024. this.meshes.splice(index, 1);
  26025. }
  26026. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26027. if (recursive) {
  26028. toRemove.getChildMeshes().forEach(function (m) {
  26029. _this.removeMesh(m);
  26030. });
  26031. }
  26032. return index;
  26033. };
  26034. /**
  26035. * Add a transform node to the list of scene's transform nodes
  26036. * @param newTransformNode defines the transform node to add
  26037. */
  26038. Scene.prototype.addTransformNode = function (newTransformNode) {
  26039. this.transformNodes.push(newTransformNode);
  26040. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26041. };
  26042. /**
  26043. * Remove a transform node for the list of scene's transform nodes
  26044. * @param toRemove defines the transform node to remove
  26045. * @returns the index where the transform node was in the transform node list
  26046. */
  26047. Scene.prototype.removeTransformNode = function (toRemove) {
  26048. var index = this.transformNodes.indexOf(toRemove);
  26049. if (index !== -1) {
  26050. // Remove from the scene if found
  26051. this.transformNodes.splice(index, 1);
  26052. }
  26053. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26054. return index;
  26055. };
  26056. /**
  26057. * Remove a skeleton for the list of scene's skeletons
  26058. * @param toRemove defines the skeleton to remove
  26059. * @returns the index where the skeleton was in the skeleton list
  26060. */
  26061. Scene.prototype.removeSkeleton = function (toRemove) {
  26062. var index = this.skeletons.indexOf(toRemove);
  26063. if (index !== -1) {
  26064. // Remove from the scene if found
  26065. this.skeletons.splice(index, 1);
  26066. }
  26067. return index;
  26068. };
  26069. /**
  26070. * Remove a morph target for the list of scene's morph targets
  26071. * @param toRemove defines the morph target to remove
  26072. * @returns the index where the morph target was in the morph target list
  26073. */
  26074. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26075. var index = this.morphTargetManagers.indexOf(toRemove);
  26076. if (index !== -1) {
  26077. // Remove from the scene if found
  26078. this.morphTargetManagers.splice(index, 1);
  26079. }
  26080. return index;
  26081. };
  26082. /**
  26083. * Remove a light for the list of scene's lights
  26084. * @param toRemove defines the light to remove
  26085. * @returns the index where the light was in the light list
  26086. */
  26087. Scene.prototype.removeLight = function (toRemove) {
  26088. var index = this.lights.indexOf(toRemove);
  26089. if (index !== -1) {
  26090. // Remove from meshes
  26091. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26092. var mesh = _a[_i];
  26093. mesh._removeLightSource(toRemove);
  26094. }
  26095. // Remove from the scene if mesh found
  26096. this.lights.splice(index, 1);
  26097. this.sortLightsByPriority();
  26098. }
  26099. this.onLightRemovedObservable.notifyObservers(toRemove);
  26100. return index;
  26101. };
  26102. /**
  26103. * Remove a camera for the list of scene's cameras
  26104. * @param toRemove defines the camera to remove
  26105. * @returns the index where the camera was in the camera list
  26106. */
  26107. Scene.prototype.removeCamera = function (toRemove) {
  26108. var index = this.cameras.indexOf(toRemove);
  26109. if (index !== -1) {
  26110. // Remove from the scene if mesh found
  26111. this.cameras.splice(index, 1);
  26112. }
  26113. // Remove from activeCameras
  26114. var index2 = this.activeCameras.indexOf(toRemove);
  26115. if (index2 !== -1) {
  26116. // Remove from the scene if mesh found
  26117. this.activeCameras.splice(index2, 1);
  26118. }
  26119. // Reset the activeCamera
  26120. if (this.activeCamera === toRemove) {
  26121. if (this.cameras.length > 0) {
  26122. this.activeCamera = this.cameras[0];
  26123. }
  26124. else {
  26125. this.activeCamera = null;
  26126. }
  26127. }
  26128. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26129. return index;
  26130. };
  26131. /**
  26132. * Remove a particle system for the list of scene's particle systems
  26133. * @param toRemove defines the particle system to remove
  26134. * @returns the index where the particle system was in the particle system list
  26135. */
  26136. Scene.prototype.removeParticleSystem = function (toRemove) {
  26137. var index = this.particleSystems.indexOf(toRemove);
  26138. if (index !== -1) {
  26139. this.particleSystems.splice(index, 1);
  26140. }
  26141. return index;
  26142. };
  26143. /**
  26144. * Remove a animation for the list of scene's animations
  26145. * @param toRemove defines the animation to remove
  26146. * @returns the index where the animation was in the animation list
  26147. */
  26148. Scene.prototype.removeAnimation = function (toRemove) {
  26149. var index = this.animations.indexOf(toRemove);
  26150. if (index !== -1) {
  26151. this.animations.splice(index, 1);
  26152. }
  26153. return index;
  26154. };
  26155. /**
  26156. * Removes the given animation group from this scene.
  26157. * @param toRemove The animation group to remove
  26158. * @returns The index of the removed animation group
  26159. */
  26160. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26161. var index = this.animationGroups.indexOf(toRemove);
  26162. if (index !== -1) {
  26163. this.animationGroups.splice(index, 1);
  26164. }
  26165. return index;
  26166. };
  26167. /**
  26168. * Removes the given multi-material from this scene.
  26169. * @param toRemove The multi-material to remove
  26170. * @returns The index of the removed multi-material
  26171. */
  26172. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26173. var index = this.multiMaterials.indexOf(toRemove);
  26174. if (index !== -1) {
  26175. this.multiMaterials.splice(index, 1);
  26176. }
  26177. return index;
  26178. };
  26179. /**
  26180. * Removes the given material from this scene.
  26181. * @param toRemove The material to remove
  26182. * @returns The index of the removed material
  26183. */
  26184. Scene.prototype.removeMaterial = function (toRemove) {
  26185. var index = this.materials.indexOf(toRemove);
  26186. if (index !== -1) {
  26187. this.materials.splice(index, 1);
  26188. }
  26189. return index;
  26190. };
  26191. /**
  26192. * Removes the given lens flare system from this scene.
  26193. * @param toRemove The lens flare system to remove
  26194. * @returns The index of the removed lens flare system
  26195. */
  26196. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26197. var index = this.lensFlareSystems.indexOf(toRemove);
  26198. if (index !== -1) {
  26199. this.lensFlareSystems.splice(index, 1);
  26200. }
  26201. return index;
  26202. };
  26203. /**
  26204. * Removes the given action manager from this scene.
  26205. * @param toRemove The action manager to remove
  26206. * @returns The index of the removed action manager
  26207. */
  26208. Scene.prototype.removeActionManager = function (toRemove) {
  26209. var index = this._actionManagers.indexOf(toRemove);
  26210. if (index !== -1) {
  26211. this._actionManagers.splice(index, 1);
  26212. }
  26213. return index;
  26214. };
  26215. /**
  26216. * Removes the given effect layer from this scene.
  26217. * @param toRemove defines the effect layer to remove
  26218. * @returns the index of the removed effect layer
  26219. */
  26220. Scene.prototype.removeEffectLayer = function (toRemove) {
  26221. var index = this.effectLayers.indexOf(toRemove);
  26222. if (index !== -1) {
  26223. this.effectLayers.splice(index, 1);
  26224. }
  26225. return index;
  26226. };
  26227. /**
  26228. * Removes the given texture from this scene.
  26229. * @param toRemove The texture to remove
  26230. * @returns The index of the removed texture
  26231. */
  26232. Scene.prototype.removeTexture = function (toRemove) {
  26233. var index = this.textures.indexOf(toRemove);
  26234. if (index !== -1) {
  26235. this.textures.splice(index, 1);
  26236. }
  26237. return index;
  26238. };
  26239. /**
  26240. * Adds the given light to this scene
  26241. * @param newLight The light to add
  26242. */
  26243. Scene.prototype.addLight = function (newLight) {
  26244. this.lights.push(newLight);
  26245. this.sortLightsByPriority();
  26246. // Add light to all meshes (To support if the light is removed and then readded)
  26247. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26248. var mesh = _a[_i];
  26249. if (mesh._lightSources.indexOf(newLight) === -1) {
  26250. mesh._lightSources.push(newLight);
  26251. mesh._resyncLightSources();
  26252. }
  26253. }
  26254. this.onNewLightAddedObservable.notifyObservers(newLight);
  26255. };
  26256. /**
  26257. * Sorts the list list based on light priorities
  26258. */
  26259. Scene.prototype.sortLightsByPriority = function () {
  26260. if (this.requireLightSorting) {
  26261. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26262. }
  26263. };
  26264. /**
  26265. * Adds the given camera to this scene
  26266. * @param newCamera The camera to add
  26267. */
  26268. Scene.prototype.addCamera = function (newCamera) {
  26269. this.cameras.push(newCamera);
  26270. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26271. };
  26272. /**
  26273. * Adds the given skeleton to this scene
  26274. * @param newSkeleton The skeleton to add
  26275. */
  26276. Scene.prototype.addSkeleton = function (newSkeleton) {
  26277. this.skeletons.push(newSkeleton);
  26278. };
  26279. /**
  26280. * Adds the given particle system to this scene
  26281. * @param newParticleSystem The particle system to add
  26282. */
  26283. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26284. this.particleSystems.push(newParticleSystem);
  26285. };
  26286. /**
  26287. * Adds the given animation to this scene
  26288. * @param newAnimation The animation to add
  26289. */
  26290. Scene.prototype.addAnimation = function (newAnimation) {
  26291. this.animations.push(newAnimation);
  26292. };
  26293. /**
  26294. * Adds the given animation group to this scene.
  26295. * @param newAnimationGroup The animation group to add
  26296. */
  26297. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26298. this.animationGroups.push(newAnimationGroup);
  26299. };
  26300. /**
  26301. * Adds the given multi-material to this scene
  26302. * @param newMultiMaterial The multi-material to add
  26303. */
  26304. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26305. this.multiMaterials.push(newMultiMaterial);
  26306. };
  26307. /**
  26308. * Adds the given material to this scene
  26309. * @param newMaterial The material to add
  26310. */
  26311. Scene.prototype.addMaterial = function (newMaterial) {
  26312. this.materials.push(newMaterial);
  26313. };
  26314. /**
  26315. * Adds the given morph target to this scene
  26316. * @param newMorphTargetManager The morph target to add
  26317. */
  26318. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26319. this.morphTargetManagers.push(newMorphTargetManager);
  26320. };
  26321. /**
  26322. * Adds the given geometry to this scene
  26323. * @param newGeometry The geometry to add
  26324. */
  26325. Scene.prototype.addGeometry = function (newGeometry) {
  26326. this._geometries.push(newGeometry);
  26327. };
  26328. /**
  26329. * Adds the given lens flare system to this scene
  26330. * @param newLensFlareSystem The lens flare system to add
  26331. */
  26332. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26333. this.lensFlareSystems.push(newLensFlareSystem);
  26334. };
  26335. /**
  26336. * Adds the given effect layer to this scene
  26337. * @param newEffectLayer defines the effect layer to add
  26338. */
  26339. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26340. this.effectLayers.push(newEffectLayer);
  26341. };
  26342. /**
  26343. * Adds the given action manager to this scene
  26344. * @param newActionManager The action manager to add
  26345. */
  26346. Scene.prototype.addActionManager = function (newActionManager) {
  26347. this._actionManagers.push(newActionManager);
  26348. };
  26349. /**
  26350. * Adds the given texture to this scene.
  26351. * @param newTexture The texture to add
  26352. */
  26353. Scene.prototype.addTexture = function (newTexture) {
  26354. this.textures.push(newTexture);
  26355. };
  26356. /**
  26357. * Switch active camera
  26358. * @param newCamera defines the new active camera
  26359. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26360. */
  26361. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26362. if (attachControl === void 0) { attachControl = true; }
  26363. var canvas = this._engine.getRenderingCanvas();
  26364. if (!canvas) {
  26365. return;
  26366. }
  26367. if (this.activeCamera) {
  26368. this.activeCamera.detachControl(canvas);
  26369. }
  26370. this.activeCamera = newCamera;
  26371. if (attachControl) {
  26372. newCamera.attachControl(canvas);
  26373. }
  26374. };
  26375. /**
  26376. * sets the active camera of the scene using its ID
  26377. * @param id defines the camera's ID
  26378. * @return the new active camera or null if none found.
  26379. */
  26380. Scene.prototype.setActiveCameraByID = function (id) {
  26381. var camera = this.getCameraByID(id);
  26382. if (camera) {
  26383. this.activeCamera = camera;
  26384. return camera;
  26385. }
  26386. return null;
  26387. };
  26388. /**
  26389. * sets the active camera of the scene using its name
  26390. * @param name defines the camera's name
  26391. * @returns the new active camera or null if none found.
  26392. */
  26393. Scene.prototype.setActiveCameraByName = function (name) {
  26394. var camera = this.getCameraByName(name);
  26395. if (camera) {
  26396. this.activeCamera = camera;
  26397. return camera;
  26398. }
  26399. return null;
  26400. };
  26401. /**
  26402. * get an animation group using its name
  26403. * @param name defines the material's name
  26404. * @return the animation group or null if none found.
  26405. */
  26406. Scene.prototype.getAnimationGroupByName = function (name) {
  26407. for (var index = 0; index < this.animationGroups.length; index++) {
  26408. if (this.animationGroups[index].name === name) {
  26409. return this.animationGroups[index];
  26410. }
  26411. }
  26412. return null;
  26413. };
  26414. /**
  26415. * get a material using its id
  26416. * @param id defines the material's ID
  26417. * @return the material or null if none found.
  26418. */
  26419. Scene.prototype.getMaterialByID = function (id) {
  26420. for (var index = 0; index < this.materials.length; index++) {
  26421. if (this.materials[index].id === id) {
  26422. return this.materials[index];
  26423. }
  26424. }
  26425. return null;
  26426. };
  26427. /**
  26428. * Gets a material using its name
  26429. * @param name defines the material's name
  26430. * @return the material or null if none found.
  26431. */
  26432. Scene.prototype.getMaterialByName = function (name) {
  26433. for (var index = 0; index < this.materials.length; index++) {
  26434. if (this.materials[index].name === name) {
  26435. return this.materials[index];
  26436. }
  26437. }
  26438. return null;
  26439. };
  26440. /**
  26441. * Gets a lens flare system using its name
  26442. * @param name defines the name to look for
  26443. * @returns the lens flare system or null if not found
  26444. */
  26445. Scene.prototype.getLensFlareSystemByName = function (name) {
  26446. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26447. if (this.lensFlareSystems[index].name === name) {
  26448. return this.lensFlareSystems[index];
  26449. }
  26450. }
  26451. return null;
  26452. };
  26453. /**
  26454. * Gets a lens flare system using its id
  26455. * @param id defines the id to look for
  26456. * @returns the lens flare system or null if not found
  26457. */
  26458. Scene.prototype.getLensFlareSystemByID = function (id) {
  26459. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26460. if (this.lensFlareSystems[index].id === id) {
  26461. return this.lensFlareSystems[index];
  26462. }
  26463. }
  26464. return null;
  26465. };
  26466. /**
  26467. * Gets a camera using its id
  26468. * @param id defines the id to look for
  26469. * @returns the camera or null if not found
  26470. */
  26471. Scene.prototype.getCameraByID = function (id) {
  26472. for (var index = 0; index < this.cameras.length; index++) {
  26473. if (this.cameras[index].id === id) {
  26474. return this.cameras[index];
  26475. }
  26476. }
  26477. return null;
  26478. };
  26479. /**
  26480. * Gets a camera using its unique id
  26481. * @param uniqueId defines the unique id to look for
  26482. * @returns the camera or null if not found
  26483. */
  26484. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26485. for (var index = 0; index < this.cameras.length; index++) {
  26486. if (this.cameras[index].uniqueId === uniqueId) {
  26487. return this.cameras[index];
  26488. }
  26489. }
  26490. return null;
  26491. };
  26492. /**
  26493. * Gets a camera using its name
  26494. * @param name defines the camera's name
  26495. * @return the camera or null if none found.
  26496. */
  26497. Scene.prototype.getCameraByName = function (name) {
  26498. for (var index = 0; index < this.cameras.length; index++) {
  26499. if (this.cameras[index].name === name) {
  26500. return this.cameras[index];
  26501. }
  26502. }
  26503. return null;
  26504. };
  26505. /**
  26506. * Gets a bone using its id
  26507. * @param id defines the bone's id
  26508. * @return the bone or null if not found
  26509. */
  26510. Scene.prototype.getBoneByID = function (id) {
  26511. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26512. var skeleton = this.skeletons[skeletonIndex];
  26513. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26514. if (skeleton.bones[boneIndex].id === id) {
  26515. return skeleton.bones[boneIndex];
  26516. }
  26517. }
  26518. }
  26519. return null;
  26520. };
  26521. /**
  26522. * Gets a bone using its id
  26523. * @param name defines the bone's name
  26524. * @return the bone or null if not found
  26525. */
  26526. Scene.prototype.getBoneByName = function (name) {
  26527. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26528. var skeleton = this.skeletons[skeletonIndex];
  26529. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26530. if (skeleton.bones[boneIndex].name === name) {
  26531. return skeleton.bones[boneIndex];
  26532. }
  26533. }
  26534. }
  26535. return null;
  26536. };
  26537. /**
  26538. * Gets a light node using its name
  26539. * @param name defines the the light's name
  26540. * @return the light or null if none found.
  26541. */
  26542. Scene.prototype.getLightByName = function (name) {
  26543. for (var index = 0; index < this.lights.length; index++) {
  26544. if (this.lights[index].name === name) {
  26545. return this.lights[index];
  26546. }
  26547. }
  26548. return null;
  26549. };
  26550. /**
  26551. * Gets a light node using its id
  26552. * @param id defines the light's id
  26553. * @return the light or null if none found.
  26554. */
  26555. Scene.prototype.getLightByID = function (id) {
  26556. for (var index = 0; index < this.lights.length; index++) {
  26557. if (this.lights[index].id === id) {
  26558. return this.lights[index];
  26559. }
  26560. }
  26561. return null;
  26562. };
  26563. /**
  26564. * Gets a light node using its scene-generated unique ID
  26565. * @param uniqueId defines the light's unique id
  26566. * @return the light or null if none found.
  26567. */
  26568. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26569. for (var index = 0; index < this.lights.length; index++) {
  26570. if (this.lights[index].uniqueId === uniqueId) {
  26571. return this.lights[index];
  26572. }
  26573. }
  26574. return null;
  26575. };
  26576. /**
  26577. * Gets a particle system by id
  26578. * @param id defines the particle system id
  26579. * @return the corresponding system or null if none found
  26580. */
  26581. Scene.prototype.getParticleSystemByID = function (id) {
  26582. for (var index = 0; index < this.particleSystems.length; index++) {
  26583. if (this.particleSystems[index].id === id) {
  26584. return this.particleSystems[index];
  26585. }
  26586. }
  26587. return null;
  26588. };
  26589. /**
  26590. * Gets a geometry using its ID
  26591. * @param id defines the geometry's id
  26592. * @return the geometry or null if none found.
  26593. */
  26594. Scene.prototype.getGeometryByID = function (id) {
  26595. for (var index = 0; index < this._geometries.length; index++) {
  26596. if (this._geometries[index].id === id) {
  26597. return this._geometries[index];
  26598. }
  26599. }
  26600. return null;
  26601. };
  26602. /**
  26603. * Add a new geometry to this scene
  26604. * @param geometry defines the geometry to be added to the scene.
  26605. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26606. * @return a boolean defining if the geometry was added or not
  26607. */
  26608. Scene.prototype.pushGeometry = function (geometry, force) {
  26609. if (!force && this.getGeometryByID(geometry.id)) {
  26610. return false;
  26611. }
  26612. this._geometries.push(geometry);
  26613. //notify the collision coordinator
  26614. if (this.collisionCoordinator) {
  26615. this.collisionCoordinator.onGeometryAdded(geometry);
  26616. }
  26617. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26618. return true;
  26619. };
  26620. /**
  26621. * Removes an existing geometry
  26622. * @param geometry defines the geometry to be removed from the scene
  26623. * @return a boolean defining if the geometry was removed or not
  26624. */
  26625. Scene.prototype.removeGeometry = function (geometry) {
  26626. var index = this._geometries.indexOf(geometry);
  26627. if (index > -1) {
  26628. this._geometries.splice(index, 1);
  26629. //notify the collision coordinator
  26630. if (this.collisionCoordinator) {
  26631. this.collisionCoordinator.onGeometryDeleted(geometry);
  26632. }
  26633. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26634. return true;
  26635. }
  26636. return false;
  26637. };
  26638. /**
  26639. * Gets the list of geometries attached to the scene
  26640. * @returns an array of Geometry
  26641. */
  26642. Scene.prototype.getGeometries = function () {
  26643. return this._geometries;
  26644. };
  26645. /**
  26646. * Gets the first added mesh found of a given ID
  26647. * @param id defines the id to search for
  26648. * @return the mesh found or null if not found at all
  26649. */
  26650. Scene.prototype.getMeshByID = function (id) {
  26651. for (var index = 0; index < this.meshes.length; index++) {
  26652. if (this.meshes[index].id === id) {
  26653. return this.meshes[index];
  26654. }
  26655. }
  26656. return null;
  26657. };
  26658. /**
  26659. * Gets a list of meshes using their id
  26660. * @param id defines the id to search for
  26661. * @returns a list of meshes
  26662. */
  26663. Scene.prototype.getMeshesByID = function (id) {
  26664. return this.meshes.filter(function (m) {
  26665. return m.id === id;
  26666. });
  26667. };
  26668. /**
  26669. * Gets the first added transform node found of a given ID
  26670. * @param id defines the id to search for
  26671. * @return the found transform node or null if not found at all.
  26672. */
  26673. Scene.prototype.getTransformNodeByID = function (id) {
  26674. for (var index = 0; index < this.transformNodes.length; index++) {
  26675. if (this.transformNodes[index].id === id) {
  26676. return this.transformNodes[index];
  26677. }
  26678. }
  26679. return null;
  26680. };
  26681. /**
  26682. * Gets a list of transform nodes using their id
  26683. * @param id defines the id to search for
  26684. * @returns a list of transform nodes
  26685. */
  26686. Scene.prototype.getTransformNodesByID = function (id) {
  26687. return this.transformNodes.filter(function (m) {
  26688. return m.id === id;
  26689. });
  26690. };
  26691. /**
  26692. * Gets a mesh with its auto-generated unique id
  26693. * @param uniqueId defines the unique id to search for
  26694. * @return the found mesh or null if not found at all.
  26695. */
  26696. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26697. for (var index = 0; index < this.meshes.length; index++) {
  26698. if (this.meshes[index].uniqueId === uniqueId) {
  26699. return this.meshes[index];
  26700. }
  26701. }
  26702. return null;
  26703. };
  26704. /**
  26705. * Gets a the last added mesh using a given id
  26706. * @param id defines the id to search for
  26707. * @return the found mesh or null if not found at all.
  26708. */
  26709. Scene.prototype.getLastMeshByID = function (id) {
  26710. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26711. if (this.meshes[index].id === id) {
  26712. return this.meshes[index];
  26713. }
  26714. }
  26715. return null;
  26716. };
  26717. /**
  26718. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26719. * @param id defines the id to search for
  26720. * @return the found node or null if not found at all
  26721. */
  26722. Scene.prototype.getLastEntryByID = function (id) {
  26723. var index;
  26724. for (index = this.meshes.length - 1; index >= 0; index--) {
  26725. if (this.meshes[index].id === id) {
  26726. return this.meshes[index];
  26727. }
  26728. }
  26729. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26730. if (this.transformNodes[index].id === id) {
  26731. return this.transformNodes[index];
  26732. }
  26733. }
  26734. for (index = this.cameras.length - 1; index >= 0; index--) {
  26735. if (this.cameras[index].id === id) {
  26736. return this.cameras[index];
  26737. }
  26738. }
  26739. for (index = this.lights.length - 1; index >= 0; index--) {
  26740. if (this.lights[index].id === id) {
  26741. return this.lights[index];
  26742. }
  26743. }
  26744. return null;
  26745. };
  26746. /**
  26747. * Gets a node (Mesh, Camera, Light) using a given id
  26748. * @param id defines the id to search for
  26749. * @return the found node or null if not found at all
  26750. */
  26751. Scene.prototype.getNodeByID = function (id) {
  26752. var mesh = this.getMeshByID(id);
  26753. if (mesh) {
  26754. return mesh;
  26755. }
  26756. var light = this.getLightByID(id);
  26757. if (light) {
  26758. return light;
  26759. }
  26760. var camera = this.getCameraByID(id);
  26761. if (camera) {
  26762. return camera;
  26763. }
  26764. var bone = this.getBoneByID(id);
  26765. return bone;
  26766. };
  26767. /**
  26768. * Gets a node (Mesh, Camera, Light) using a given name
  26769. * @param name defines the name to search for
  26770. * @return the found node or null if not found at all.
  26771. */
  26772. Scene.prototype.getNodeByName = function (name) {
  26773. var mesh = this.getMeshByName(name);
  26774. if (mesh) {
  26775. return mesh;
  26776. }
  26777. var light = this.getLightByName(name);
  26778. if (light) {
  26779. return light;
  26780. }
  26781. var camera = this.getCameraByName(name);
  26782. if (camera) {
  26783. return camera;
  26784. }
  26785. var bone = this.getBoneByName(name);
  26786. return bone;
  26787. };
  26788. /**
  26789. * Gets a mesh using a given name
  26790. * @param name defines the name to search for
  26791. * @return the found mesh or null if not found at all.
  26792. */
  26793. Scene.prototype.getMeshByName = function (name) {
  26794. for (var index = 0; index < this.meshes.length; index++) {
  26795. if (this.meshes[index].name === name) {
  26796. return this.meshes[index];
  26797. }
  26798. }
  26799. return null;
  26800. };
  26801. /**
  26802. * Gets a transform node using a given name
  26803. * @param name defines the name to search for
  26804. * @return the found transform node or null if not found at all.
  26805. */
  26806. Scene.prototype.getTransformNodeByName = function (name) {
  26807. for (var index = 0; index < this.transformNodes.length; index++) {
  26808. if (this.transformNodes[index].name === name) {
  26809. return this.transformNodes[index];
  26810. }
  26811. }
  26812. return null;
  26813. };
  26814. /**
  26815. * Gets a sound using a given name
  26816. * @param name defines the name to search for
  26817. * @return the found sound or null if not found at all.
  26818. */
  26819. Scene.prototype.getSoundByName = function (name) {
  26820. var index;
  26821. if (BABYLON.AudioEngine) {
  26822. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26823. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26824. return this.mainSoundTrack.soundCollection[index];
  26825. }
  26826. }
  26827. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26828. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26829. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26830. return this.soundTracks[sdIndex].soundCollection[index];
  26831. }
  26832. }
  26833. }
  26834. }
  26835. return null;
  26836. };
  26837. /**
  26838. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26839. * @param id defines the id to search for
  26840. * @return the found skeleton or null if not found at all.
  26841. */
  26842. Scene.prototype.getLastSkeletonByID = function (id) {
  26843. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26844. if (this.skeletons[index].id === id) {
  26845. return this.skeletons[index];
  26846. }
  26847. }
  26848. return null;
  26849. };
  26850. /**
  26851. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26852. * @param id defines the id to search for
  26853. * @return the found skeleton or null if not found at all.
  26854. */
  26855. Scene.prototype.getSkeletonById = function (id) {
  26856. for (var index = 0; index < this.skeletons.length; index++) {
  26857. if (this.skeletons[index].id === id) {
  26858. return this.skeletons[index];
  26859. }
  26860. }
  26861. return null;
  26862. };
  26863. /**
  26864. * Gets a skeleton using a given name
  26865. * @param name defines the name to search for
  26866. * @return the found skeleton or null if not found at all.
  26867. */
  26868. Scene.prototype.getSkeletonByName = function (name) {
  26869. for (var index = 0; index < this.skeletons.length; index++) {
  26870. if (this.skeletons[index].name === name) {
  26871. return this.skeletons[index];
  26872. }
  26873. }
  26874. return null;
  26875. };
  26876. /**
  26877. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26878. * @param id defines the id to search for
  26879. * @return the found morph target manager or null if not found at all.
  26880. */
  26881. Scene.prototype.getMorphTargetManagerById = function (id) {
  26882. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26883. if (this.morphTargetManagers[index].uniqueId === id) {
  26884. return this.morphTargetManagers[index];
  26885. }
  26886. }
  26887. return null;
  26888. };
  26889. /**
  26890. * Gets a boolean indicating if the given mesh is active
  26891. * @param mesh defines the mesh to look for
  26892. * @returns true if the mesh is in the active list
  26893. */
  26894. Scene.prototype.isActiveMesh = function (mesh) {
  26895. return (this._activeMeshes.indexOf(mesh) !== -1);
  26896. };
  26897. /**
  26898. * Return a the first highlight layer of the scene with a given name.
  26899. * @param name The name of the highlight layer to look for.
  26900. * @return The highlight layer if found otherwise null.
  26901. */
  26902. Scene.prototype.getHighlightLayerByName = function (name) {
  26903. for (var index = 0; index < this.effectLayers.length; index++) {
  26904. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26905. return this.effectLayers[index];
  26906. }
  26907. }
  26908. return null;
  26909. };
  26910. /**
  26911. * Return a the first highlight layer of the scene with a given name.
  26912. * @param name The name of the highlight layer to look for.
  26913. * @return The highlight layer if found otherwise null.
  26914. */
  26915. Scene.prototype.getGlowLayerByName = function (name) {
  26916. for (var index = 0; index < this.effectLayers.length; index++) {
  26917. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26918. return this.effectLayers[index];
  26919. }
  26920. }
  26921. return null;
  26922. };
  26923. Object.defineProperty(Scene.prototype, "uid", {
  26924. /**
  26925. * Return a unique id as a string which can serve as an identifier for the scene
  26926. */
  26927. get: function () {
  26928. if (!this._uid) {
  26929. this._uid = BABYLON.Tools.RandomId();
  26930. }
  26931. return this._uid;
  26932. },
  26933. enumerable: true,
  26934. configurable: true
  26935. });
  26936. /**
  26937. * Add an externaly attached data from its key.
  26938. * This method call will fail and return false, if such key already exists.
  26939. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26940. * @param key the unique key that identifies the data
  26941. * @param data the data object to associate to the key for this Engine instance
  26942. * @return true if no such key were already present and the data was added successfully, false otherwise
  26943. */
  26944. Scene.prototype.addExternalData = function (key, data) {
  26945. if (!this._externalData) {
  26946. this._externalData = new BABYLON.StringDictionary();
  26947. }
  26948. return this._externalData.add(key, data);
  26949. };
  26950. /**
  26951. * Get an externaly attached data from its key
  26952. * @param key the unique key that identifies the data
  26953. * @return the associated data, if present (can be null), or undefined if not present
  26954. */
  26955. Scene.prototype.getExternalData = function (key) {
  26956. if (!this._externalData) {
  26957. return null;
  26958. }
  26959. return this._externalData.get(key);
  26960. };
  26961. /**
  26962. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26963. * @param key the unique key that identifies the data
  26964. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26965. * @return the associated data, can be null if the factory returned null.
  26966. */
  26967. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26968. if (!this._externalData) {
  26969. this._externalData = new BABYLON.StringDictionary();
  26970. }
  26971. return this._externalData.getOrAddWithFactory(key, factory);
  26972. };
  26973. /**
  26974. * Remove an externaly attached data from the Engine instance
  26975. * @param key the unique key that identifies the data
  26976. * @return true if the data was successfully removed, false if it doesn't exist
  26977. */
  26978. Scene.prototype.removeExternalData = function (key) {
  26979. return this._externalData.remove(key);
  26980. };
  26981. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26982. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26983. if (mesh.showSubMeshesBoundingBox) {
  26984. var boundingInfo = subMesh.getBoundingInfo();
  26985. if (boundingInfo !== null && boundingInfo !== undefined) {
  26986. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26987. }
  26988. }
  26989. var material = subMesh.getMaterial();
  26990. if (material !== null && material !== undefined) {
  26991. // Render targets
  26992. if (material.getRenderTargetTextures !== undefined) {
  26993. if (this._processedMaterials.indexOf(material) === -1) {
  26994. this._processedMaterials.push(material);
  26995. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26996. }
  26997. }
  26998. // Dispatch
  26999. this._activeIndices.addCount(subMesh.indexCount, false);
  27000. this._renderingManager.dispatch(subMesh, mesh, material);
  27001. }
  27002. }
  27003. };
  27004. /**
  27005. * Clear the processed materials smart array preventing retention point in material dispose.
  27006. */
  27007. Scene.prototype.freeProcessedMaterials = function () {
  27008. this._processedMaterials.dispose();
  27009. };
  27010. /**
  27011. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27012. */
  27013. Scene.prototype.freeActiveMeshes = function () {
  27014. this._activeMeshes.dispose();
  27015. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27016. this.activeCamera._activeMeshes.dispose();
  27017. }
  27018. if (this.activeCameras) {
  27019. for (var i = 0; i < this.activeCameras.length; i++) {
  27020. var activeCamera = this.activeCameras[i];
  27021. if (activeCamera && activeCamera._activeMeshes) {
  27022. activeCamera._activeMeshes.dispose();
  27023. }
  27024. }
  27025. }
  27026. };
  27027. /**
  27028. * Clear the info related to rendering groups preventing retention points during dispose.
  27029. */
  27030. Scene.prototype.freeRenderingGroups = function () {
  27031. if (this._renderingManager) {
  27032. this._renderingManager.freeRenderingGroups();
  27033. }
  27034. if (this.textures) {
  27035. for (var i = 0; i < this.textures.length; i++) {
  27036. var texture = this.textures[i];
  27037. if (texture && texture.renderList) {
  27038. texture.freeRenderingGroups();
  27039. }
  27040. }
  27041. }
  27042. };
  27043. /** @hidden */
  27044. Scene.prototype._isInIntermediateRendering = function () {
  27045. return this._intermediateRendering;
  27046. };
  27047. /**
  27048. * Defines the current active mesh candidate provider
  27049. * @param provider defines the provider to use
  27050. */
  27051. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27052. this._activeMeshCandidateProvider = provider;
  27053. };
  27054. /**
  27055. * Gets the current active mesh candidate provider
  27056. * @returns the current active mesh candidate provider
  27057. */
  27058. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27059. return this._activeMeshCandidateProvider;
  27060. };
  27061. /**
  27062. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27063. * @returns the current scene
  27064. */
  27065. Scene.prototype.freezeActiveMeshes = function () {
  27066. if (!this.activeCamera) {
  27067. return this;
  27068. }
  27069. if (!this._frustumPlanes) {
  27070. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27071. }
  27072. this._evaluateActiveMeshes();
  27073. this._activeMeshesFrozen = true;
  27074. return this;
  27075. };
  27076. /**
  27077. * Use this function to restart evaluating active meshes on every frame
  27078. * @returns the current scene
  27079. */
  27080. Scene.prototype.unfreezeActiveMeshes = function () {
  27081. this._activeMeshesFrozen = false;
  27082. return this;
  27083. };
  27084. Scene.prototype._evaluateActiveMeshes = function () {
  27085. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27086. return;
  27087. }
  27088. if (!this.activeCamera) {
  27089. return;
  27090. }
  27091. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27092. this.activeCamera._activeMeshes.reset();
  27093. this._activeMeshes.reset();
  27094. this._renderingManager.reset();
  27095. this._processedMaterials.reset();
  27096. this._activeParticleSystems.reset();
  27097. this._activeSkeletons.reset();
  27098. this._softwareSkinnedMeshes.reset();
  27099. if (this._boundingBoxRenderer) {
  27100. this._boundingBoxRenderer.reset();
  27101. }
  27102. // Meshes
  27103. var meshes;
  27104. var len;
  27105. var checkIsEnabled = true;
  27106. // Determine mesh candidates
  27107. if (this._activeMeshCandidateProvider !== undefined) {
  27108. // Use _activeMeshCandidateProvider
  27109. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27110. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27111. if (meshes !== undefined) {
  27112. len = meshes.length;
  27113. }
  27114. else {
  27115. len = 0;
  27116. }
  27117. }
  27118. else if (this._selectionOctree !== undefined) {
  27119. // Octree
  27120. var selection = this._selectionOctree.select(this._frustumPlanes);
  27121. meshes = selection.data;
  27122. len = selection.length;
  27123. }
  27124. else {
  27125. // Full scene traversal
  27126. len = this.meshes.length;
  27127. meshes = this.meshes;
  27128. }
  27129. // Check each mesh
  27130. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27131. mesh = meshes[meshIndex];
  27132. if (mesh.isBlocked) {
  27133. continue;
  27134. }
  27135. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27136. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27137. continue;
  27138. }
  27139. mesh.computeWorldMatrix();
  27140. // Intersections
  27141. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27142. this._meshesForIntersections.pushNoDuplicate(mesh);
  27143. }
  27144. // Switch to current LOD
  27145. meshLOD = mesh.getLOD(this.activeCamera);
  27146. if (meshLOD === undefined || meshLOD === null) {
  27147. continue;
  27148. }
  27149. mesh._preActivate();
  27150. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27151. this._activeMeshes.push(mesh);
  27152. this.activeCamera._activeMeshes.push(mesh);
  27153. mesh._activate(this._renderId);
  27154. if (meshLOD !== mesh) {
  27155. meshLOD._activate(this._renderId);
  27156. }
  27157. this._activeMesh(mesh, meshLOD);
  27158. }
  27159. }
  27160. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27161. // Particle systems
  27162. if (this.particlesEnabled) {
  27163. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27164. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27165. var particleSystem = this.particleSystems[particleIndex];
  27166. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27167. continue;
  27168. }
  27169. var emitter = particleSystem.emitter;
  27170. if (!emitter.position || emitter.isEnabled()) {
  27171. this._activeParticleSystems.push(particleSystem);
  27172. particleSystem.animate();
  27173. this._renderingManager.dispatchParticles(particleSystem);
  27174. }
  27175. }
  27176. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27177. }
  27178. };
  27179. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27180. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27181. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27182. mesh.skeleton.prepare();
  27183. }
  27184. if (!mesh.computeBonesUsingShaders) {
  27185. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27186. }
  27187. }
  27188. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27189. var boundingInfo = sourceMesh.getBoundingInfo();
  27190. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27191. }
  27192. if (mesh !== undefined && mesh !== null
  27193. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27194. // Submeshes Octrees
  27195. var len;
  27196. var subMeshes;
  27197. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27198. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27199. len = intersections.length;
  27200. subMeshes = intersections.data;
  27201. }
  27202. else {
  27203. subMeshes = mesh.subMeshes;
  27204. len = subMeshes.length;
  27205. }
  27206. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27207. subMesh = subMeshes[subIndex];
  27208. this._evaluateSubMesh(subMesh, mesh);
  27209. }
  27210. }
  27211. };
  27212. /**
  27213. * Update the transform matrix to update from the current active camera
  27214. * @param force defines a boolean used to force the update even if cache is up to date
  27215. */
  27216. Scene.prototype.updateTransformMatrix = function (force) {
  27217. if (!this.activeCamera) {
  27218. return;
  27219. }
  27220. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27221. };
  27222. /**
  27223. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27224. * @param alternateCamera defines the camera to use
  27225. */
  27226. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27227. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27228. };
  27229. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27230. if (camera && camera._skipRendering) {
  27231. return;
  27232. }
  27233. var engine = this._engine;
  27234. this.activeCamera = camera;
  27235. if (!this.activeCamera)
  27236. throw new Error("Active camera not set");
  27237. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27238. // Viewport
  27239. engine.setViewport(this.activeCamera.viewport);
  27240. // Camera
  27241. this.resetCachedMaterial();
  27242. this._renderId++;
  27243. this.updateTransformMatrix();
  27244. if (camera._alternateCamera) {
  27245. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27246. this._alternateRendering = true;
  27247. }
  27248. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27249. // Meshes
  27250. this._evaluateActiveMeshes();
  27251. // Software skinning
  27252. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27253. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27254. mesh.applySkeleton(mesh.skeleton);
  27255. }
  27256. // Render targets
  27257. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27258. var needsRestoreFrameBuffer = false;
  27259. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27260. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27261. }
  27262. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27263. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27264. }
  27265. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27266. this._intermediateRendering = true;
  27267. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27268. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27269. var renderTarget = this._renderTargets.data[renderIndex];
  27270. if (renderTarget._shouldRender()) {
  27271. this._renderId++;
  27272. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27273. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27274. }
  27275. }
  27276. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27277. this._intermediateRendering = false;
  27278. this._renderId++;
  27279. needsRestoreFrameBuffer = true; // Restore back buffer
  27280. }
  27281. // Render EffecttLayer Texture
  27282. var stencilState = this._engine.getStencilBuffer();
  27283. var renderEffects = false;
  27284. var needStencil = false;
  27285. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27286. this._intermediateRendering = true;
  27287. for (var i = 0; i < this.effectLayers.length; i++) {
  27288. var effectLayer = this.effectLayers[i];
  27289. if (effectLayer.shouldRender() &&
  27290. (!effectLayer.camera ||
  27291. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27292. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27293. renderEffects = true;
  27294. needStencil = needStencil || effectLayer.needStencil();
  27295. var renderTarget = effectLayer._mainTexture;
  27296. if (renderTarget._shouldRender()) {
  27297. this._renderId++;
  27298. renderTarget.render(false, false);
  27299. needsRestoreFrameBuffer = true;
  27300. }
  27301. }
  27302. }
  27303. this._intermediateRendering = false;
  27304. this._renderId++;
  27305. }
  27306. if (needsRestoreFrameBuffer) {
  27307. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27308. }
  27309. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27310. // Prepare Frame
  27311. this.postProcessManager._prepareFrame();
  27312. // Backgrounds
  27313. var layerIndex;
  27314. var layer;
  27315. if (this.layers.length) {
  27316. engine.setDepthBuffer(false);
  27317. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27318. layer = this.layers[layerIndex];
  27319. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27320. layer.render();
  27321. }
  27322. }
  27323. engine.setDepthBuffer(true);
  27324. }
  27325. // Activate effect Layer stencil
  27326. if (needStencil) {
  27327. this._engine.setStencilBuffer(true);
  27328. }
  27329. // Render
  27330. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27331. this._renderingManager.render(null, null, true, true);
  27332. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27333. // Restore effect Layer stencil
  27334. if (needStencil) {
  27335. this._engine.setStencilBuffer(stencilState);
  27336. }
  27337. // Bounding boxes
  27338. if (this._boundingBoxRenderer) {
  27339. this._boundingBoxRenderer.render();
  27340. }
  27341. // Lens flares
  27342. if (this.lensFlaresEnabled) {
  27343. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27344. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27345. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27346. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27347. lensFlareSystem.render();
  27348. }
  27349. }
  27350. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27351. }
  27352. // Effect Layer
  27353. if (renderEffects) {
  27354. engine.setDepthBuffer(false);
  27355. for (var i = 0; i < this.effectLayers.length; i++) {
  27356. if (this.effectLayers[i].shouldRender()) {
  27357. this.effectLayers[i].render();
  27358. }
  27359. }
  27360. engine.setDepthBuffer(true);
  27361. }
  27362. // Foregrounds
  27363. if (this.layers.length) {
  27364. engine.setDepthBuffer(false);
  27365. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27366. layer = this.layers[layerIndex];
  27367. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27368. layer.render();
  27369. }
  27370. }
  27371. engine.setDepthBuffer(true);
  27372. }
  27373. // Finalize frame
  27374. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27375. // Reset some special arrays
  27376. this._renderTargets.reset();
  27377. this._alternateRendering = false;
  27378. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27379. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27380. };
  27381. Scene.prototype._processSubCameras = function (camera) {
  27382. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27383. this._renderForCamera(camera);
  27384. return;
  27385. }
  27386. // rig cameras
  27387. for (var index = 0; index < camera._rigCameras.length; index++) {
  27388. this._renderForCamera(camera._rigCameras[index], camera);
  27389. }
  27390. this.activeCamera = camera;
  27391. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27392. };
  27393. Scene.prototype._checkIntersections = function () {
  27394. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27395. var sourceMesh = this._meshesForIntersections.data[index];
  27396. if (!sourceMesh.actionManager) {
  27397. continue;
  27398. }
  27399. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27400. var action = sourceMesh.actionManager.actions[actionIndex];
  27401. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27402. var parameters = action.getTriggerParameter();
  27403. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27404. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27405. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27406. if (areIntersecting && currentIntersectionInProgress === -1) {
  27407. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27408. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27409. sourceMesh._intersectionsInProgress.push(otherMesh);
  27410. }
  27411. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27412. sourceMesh._intersectionsInProgress.push(otherMesh);
  27413. }
  27414. }
  27415. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27416. //They intersected, and now they don't.
  27417. //is this trigger an exit trigger? execute an event.
  27418. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27419. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27420. }
  27421. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27422. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27423. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27424. return otherMesh === parameterMesh;
  27425. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27426. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27427. }
  27428. }
  27429. }
  27430. }
  27431. }
  27432. };
  27433. /**
  27434. * Render the scene
  27435. */
  27436. Scene.prototype.render = function () {
  27437. if (this.isDisposed) {
  27438. return;
  27439. }
  27440. this._activeParticles.fetchNewFrame();
  27441. this._totalVertices.fetchNewFrame();
  27442. this._activeIndices.fetchNewFrame();
  27443. this._activeBones.fetchNewFrame();
  27444. this._meshesForIntersections.reset();
  27445. this.resetCachedMaterial();
  27446. this.onBeforeAnimationsObservable.notifyObservers(this);
  27447. // Actions
  27448. if (this.actionManager) {
  27449. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27450. }
  27451. //Simplification Queue
  27452. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27453. this.simplificationQueue.executeNext();
  27454. }
  27455. if (this._engine.isDeterministicLockStep()) {
  27456. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27457. var defaultFPS = (60.0 / 1000.0);
  27458. var defaultFrameTime = 1000 / 60; // frame time in MS
  27459. if (this._physicsEngine) {
  27460. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27461. }
  27462. var stepsTaken = 0;
  27463. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27464. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27465. internalSteps = Math.min(internalSteps, maxSubSteps);
  27466. do {
  27467. this.onBeforeStepObservable.notifyObservers(this);
  27468. // Animations
  27469. this._animationRatio = defaultFrameTime * defaultFPS;
  27470. this._animate();
  27471. this.onAfterAnimationsObservable.notifyObservers(this);
  27472. // Physics
  27473. if (this._physicsEngine) {
  27474. this.onBeforePhysicsObservable.notifyObservers(this);
  27475. this._physicsEngine._step(defaultFrameTime / 1000);
  27476. this.onAfterPhysicsObservable.notifyObservers(this);
  27477. }
  27478. this.onAfterStepObservable.notifyObservers(this);
  27479. this._currentStepId++;
  27480. stepsTaken++;
  27481. deltaTime -= defaultFrameTime;
  27482. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27483. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27484. }
  27485. else {
  27486. // Animations
  27487. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27488. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27489. this._animate();
  27490. this.onAfterAnimationsObservable.notifyObservers(this);
  27491. // Physics
  27492. if (this._physicsEngine) {
  27493. this.onBeforePhysicsObservable.notifyObservers(this);
  27494. this._physicsEngine._step(deltaTime / 1000.0);
  27495. this.onAfterPhysicsObservable.notifyObservers(this);
  27496. }
  27497. }
  27498. // update gamepad manager
  27499. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27500. this._gamepadManager._checkGamepadsStatus();
  27501. }
  27502. // Update Cameras
  27503. if (this.activeCameras.length > 0) {
  27504. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27505. var camera = this.activeCameras[cameraIndex];
  27506. camera.update();
  27507. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27508. // rig cameras
  27509. for (var index = 0; index < camera._rigCameras.length; index++) {
  27510. camera._rigCameras[index].update();
  27511. }
  27512. }
  27513. }
  27514. }
  27515. else if (this.activeCamera) {
  27516. this.activeCamera.update();
  27517. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27518. // rig cameras
  27519. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27520. this.activeCamera._rigCameras[index].update();
  27521. }
  27522. }
  27523. }
  27524. // Before render
  27525. this.onBeforeRenderObservable.notifyObservers(this);
  27526. // Customs render targets
  27527. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27528. var engine = this.getEngine();
  27529. var currentActiveCamera = this.activeCamera;
  27530. if (this.renderTargetsEnabled) {
  27531. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27532. this._intermediateRendering = true;
  27533. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27534. var renderTarget = this.customRenderTargets[customIndex];
  27535. if (renderTarget._shouldRender()) {
  27536. this._renderId++;
  27537. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27538. if (!this.activeCamera)
  27539. throw new Error("Active camera not set");
  27540. // Viewport
  27541. engine.setViewport(this.activeCamera.viewport);
  27542. // Camera
  27543. this.updateTransformMatrix();
  27544. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27545. }
  27546. }
  27547. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27548. this._intermediateRendering = false;
  27549. this._renderId++;
  27550. }
  27551. // Restore back buffer
  27552. if (this.customRenderTargets.length > 0) {
  27553. engine.restoreDefaultFramebuffer();
  27554. }
  27555. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27556. this.activeCamera = currentActiveCamera;
  27557. // Procedural textures
  27558. if (this.proceduralTexturesEnabled) {
  27559. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27560. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27561. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27562. if (proceduralTexture._shouldRender()) {
  27563. proceduralTexture.render();
  27564. }
  27565. }
  27566. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27567. }
  27568. // Clear
  27569. if (this.autoClearDepthAndStencil || this.autoClear) {
  27570. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27571. }
  27572. // Shadows
  27573. if (this.shadowsEnabled) {
  27574. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27575. var light = this.lights[lightIndex];
  27576. var shadowGenerator = light.getShadowGenerator();
  27577. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27578. var shadowMap = (shadowGenerator.getShadowMap());
  27579. if (this.textures.indexOf(shadowMap) !== -1) {
  27580. this._renderTargets.push(shadowMap);
  27581. }
  27582. }
  27583. }
  27584. }
  27585. // Depth renderer
  27586. for (var key in this._depthRenderer) {
  27587. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27588. }
  27589. // Geometry renderer
  27590. if (this._geometryBufferRenderer) {
  27591. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27592. }
  27593. // RenderPipeline
  27594. if (this._postProcessRenderPipelineManager) {
  27595. this._postProcessRenderPipelineManager.update();
  27596. }
  27597. // Multi-cameras?
  27598. if (this.activeCameras.length > 0) {
  27599. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27600. if (cameraIndex > 0) {
  27601. this._engine.clear(null, false, true, true);
  27602. }
  27603. this._processSubCameras(this.activeCameras[cameraIndex]);
  27604. }
  27605. }
  27606. else {
  27607. if (!this.activeCamera) {
  27608. throw new Error("No camera defined");
  27609. }
  27610. this._processSubCameras(this.activeCamera);
  27611. }
  27612. // Intersection checks
  27613. this._checkIntersections();
  27614. // Update the audio listener attached to the camera
  27615. if (BABYLON.AudioEngine) {
  27616. this._updateAudioParameters();
  27617. }
  27618. // After render
  27619. if (this.afterRender) {
  27620. this.afterRender();
  27621. }
  27622. this.onAfterRenderObservable.notifyObservers(this);
  27623. // Cleaning
  27624. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27625. var data = this._toBeDisposed.data[index];
  27626. if (data) {
  27627. data.dispose();
  27628. }
  27629. this._toBeDisposed[index] = null;
  27630. }
  27631. this._toBeDisposed.reset();
  27632. if (this.dumpNextRenderTargets) {
  27633. this.dumpNextRenderTargets = false;
  27634. }
  27635. this._activeBones.addCount(0, true);
  27636. this._activeIndices.addCount(0, true);
  27637. this._activeParticles.addCount(0, true);
  27638. };
  27639. Scene.prototype._updateAudioParameters = function () {
  27640. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27641. return;
  27642. }
  27643. var listeningCamera;
  27644. var audioEngine = BABYLON.Engine.audioEngine;
  27645. if (this.activeCameras.length > 0) {
  27646. listeningCamera = this.activeCameras[0];
  27647. }
  27648. else {
  27649. listeningCamera = this.activeCamera;
  27650. }
  27651. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27652. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27653. // for VR cameras
  27654. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27655. listeningCamera = listeningCamera.rigCameras[0];
  27656. }
  27657. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27658. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27659. cameraDirection.normalize();
  27660. // To avoid some errors on GearVR
  27661. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27662. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27663. }
  27664. var i;
  27665. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27666. var sound = this.mainSoundTrack.soundCollection[i];
  27667. if (sound.useCustomAttenuation) {
  27668. sound.updateDistanceFromListener();
  27669. }
  27670. }
  27671. for (i = 0; i < this.soundTracks.length; i++) {
  27672. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27673. sound = this.soundTracks[i].soundCollection[j];
  27674. if (sound.useCustomAttenuation) {
  27675. sound.updateDistanceFromListener();
  27676. }
  27677. }
  27678. }
  27679. }
  27680. };
  27681. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27682. // Audio
  27683. /**
  27684. * Gets or sets if audio support is enabled
  27685. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27686. */
  27687. get: function () {
  27688. return this._audioEnabled;
  27689. },
  27690. set: function (value) {
  27691. this._audioEnabled = value;
  27692. if (BABYLON.AudioEngine) {
  27693. if (this._audioEnabled) {
  27694. this._enableAudio();
  27695. }
  27696. else {
  27697. this._disableAudio();
  27698. }
  27699. }
  27700. },
  27701. enumerable: true,
  27702. configurable: true
  27703. });
  27704. Scene.prototype._disableAudio = function () {
  27705. var i;
  27706. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27707. this.mainSoundTrack.soundCollection[i].pause();
  27708. }
  27709. for (i = 0; i < this.soundTracks.length; i++) {
  27710. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27711. this.soundTracks[i].soundCollection[j].pause();
  27712. }
  27713. }
  27714. };
  27715. Scene.prototype._enableAudio = function () {
  27716. var i;
  27717. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27718. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27719. this.mainSoundTrack.soundCollection[i].play();
  27720. }
  27721. }
  27722. for (i = 0; i < this.soundTracks.length; i++) {
  27723. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27724. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27725. this.soundTracks[i].soundCollection[j].play();
  27726. }
  27727. }
  27728. }
  27729. };
  27730. Object.defineProperty(Scene.prototype, "headphone", {
  27731. /**
  27732. * Gets or sets if audio will be output to headphones
  27733. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27734. */
  27735. get: function () {
  27736. return this._headphone;
  27737. },
  27738. set: function (value) {
  27739. this._headphone = value;
  27740. if (BABYLON.AudioEngine) {
  27741. if (this._headphone) {
  27742. this._switchAudioModeForHeadphones();
  27743. }
  27744. else {
  27745. this._switchAudioModeForNormalSpeakers();
  27746. }
  27747. }
  27748. },
  27749. enumerable: true,
  27750. configurable: true
  27751. });
  27752. Scene.prototype._switchAudioModeForHeadphones = function () {
  27753. this.mainSoundTrack.switchPanningModelToHRTF();
  27754. for (var i = 0; i < this.soundTracks.length; i++) {
  27755. this.soundTracks[i].switchPanningModelToHRTF();
  27756. }
  27757. };
  27758. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27759. this.mainSoundTrack.switchPanningModelToEqualPower();
  27760. for (var i = 0; i < this.soundTracks.length; i++) {
  27761. this.soundTracks[i].switchPanningModelToEqualPower();
  27762. }
  27763. };
  27764. /**
  27765. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27766. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27767. * @returns the created depth renderer
  27768. */
  27769. Scene.prototype.enableDepthRenderer = function (camera) {
  27770. camera = camera || this.activeCamera;
  27771. if (!camera) {
  27772. throw "No camera available to enable depth renderer";
  27773. }
  27774. if (!this._depthRenderer[camera.id]) {
  27775. var textureType = 0;
  27776. if (this._engine.getCaps().textureHalfFloatRender) {
  27777. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27778. }
  27779. else if (this._engine.getCaps().textureFloatRender) {
  27780. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27781. }
  27782. else {
  27783. throw "Depth renderer does not support int texture type";
  27784. }
  27785. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27786. }
  27787. return this._depthRenderer[camera.id];
  27788. };
  27789. /**
  27790. * Disables a depth renderer for a given camera
  27791. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27792. */
  27793. Scene.prototype.disableDepthRenderer = function (camera) {
  27794. camera = camera || this.activeCamera;
  27795. if (!camera || !this._depthRenderer[camera.id]) {
  27796. return;
  27797. }
  27798. this._depthRenderer[camera.id].dispose();
  27799. delete this._depthRenderer[camera.id];
  27800. };
  27801. /**
  27802. * Enables a GeometryBufferRender and associates it with the scene
  27803. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27804. * @returns the GeometryBufferRenderer
  27805. */
  27806. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27807. if (ratio === void 0) { ratio = 1; }
  27808. if (this._geometryBufferRenderer) {
  27809. return this._geometryBufferRenderer;
  27810. }
  27811. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27812. if (!this._geometryBufferRenderer.isSupported) {
  27813. this._geometryBufferRenderer = null;
  27814. }
  27815. return this._geometryBufferRenderer;
  27816. };
  27817. /**
  27818. * Disables the GeometryBufferRender associated with the scene
  27819. */
  27820. Scene.prototype.disableGeometryBufferRenderer = function () {
  27821. if (!this._geometryBufferRenderer) {
  27822. return;
  27823. }
  27824. this._geometryBufferRenderer.dispose();
  27825. this._geometryBufferRenderer = null;
  27826. };
  27827. /**
  27828. * Freeze all materials
  27829. * A frozen material will not be updatable but should be faster to render
  27830. */
  27831. Scene.prototype.freezeMaterials = function () {
  27832. for (var i = 0; i < this.materials.length; i++) {
  27833. this.materials[i].freeze();
  27834. }
  27835. };
  27836. /**
  27837. * Unfreeze all materials
  27838. * A frozen material will not be updatable but should be faster to render
  27839. */
  27840. Scene.prototype.unfreezeMaterials = function () {
  27841. for (var i = 0; i < this.materials.length; i++) {
  27842. this.materials[i].unfreeze();
  27843. }
  27844. };
  27845. /**
  27846. * Releases all held ressources
  27847. */
  27848. Scene.prototype.dispose = function () {
  27849. this.beforeRender = null;
  27850. this.afterRender = null;
  27851. this.skeletons = [];
  27852. this.morphTargetManagers = [];
  27853. this.importedMeshesFiles = new Array();
  27854. this.stopAllAnimations();
  27855. this.resetCachedMaterial();
  27856. for (var key in this._depthRenderer) {
  27857. this._depthRenderer[key].dispose();
  27858. }
  27859. if (this._gamepadManager) {
  27860. this._gamepadManager.dispose();
  27861. this._gamepadManager = null;
  27862. }
  27863. // Smart arrays
  27864. if (this.activeCamera) {
  27865. this.activeCamera._activeMeshes.dispose();
  27866. this.activeCamera = null;
  27867. }
  27868. this._activeMeshes.dispose();
  27869. this._renderingManager.dispose();
  27870. this._processedMaterials.dispose();
  27871. this._activeParticleSystems.dispose();
  27872. this._activeSkeletons.dispose();
  27873. this._softwareSkinnedMeshes.dispose();
  27874. this._renderTargets.dispose();
  27875. this._registeredForLateAnimationBindings.dispose();
  27876. if (this._boundingBoxRenderer) {
  27877. this._boundingBoxRenderer.dispose();
  27878. }
  27879. this._meshesForIntersections.dispose();
  27880. this._toBeDisposed.dispose();
  27881. // Abort active requests
  27882. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27883. var request = _a[_i];
  27884. request.abort();
  27885. }
  27886. // Debug layer
  27887. if (this._debugLayer) {
  27888. this._debugLayer.hide();
  27889. }
  27890. // Events
  27891. this.onDisposeObservable.notifyObservers(this);
  27892. this.onDisposeObservable.clear();
  27893. this.onBeforeRenderObservable.clear();
  27894. this.onAfterRenderObservable.clear();
  27895. this.onBeforeRenderTargetsRenderObservable.clear();
  27896. this.onAfterRenderTargetsRenderObservable.clear();
  27897. this.onAfterStepObservable.clear();
  27898. this.onBeforeStepObservable.clear();
  27899. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27900. this.onAfterActiveMeshesEvaluationObservable.clear();
  27901. this.onBeforeParticlesRenderingObservable.clear();
  27902. this.onAfterParticlesRenderingObservable.clear();
  27903. this.onBeforeSpritesRenderingObservable.clear();
  27904. this.onAfterSpritesRenderingObservable.clear();
  27905. this.onBeforeDrawPhaseObservable.clear();
  27906. this.onAfterDrawPhaseObservable.clear();
  27907. this.onBeforePhysicsObservable.clear();
  27908. this.onAfterPhysicsObservable.clear();
  27909. this.onBeforeAnimationsObservable.clear();
  27910. this.onAfterAnimationsObservable.clear();
  27911. this.onDataLoadedObservable.clear();
  27912. this.detachControl();
  27913. // Release sounds & sounds tracks
  27914. if (BABYLON.AudioEngine) {
  27915. this.disposeSounds();
  27916. }
  27917. // VR Helper
  27918. if (this.VRHelper) {
  27919. this.VRHelper.dispose();
  27920. }
  27921. // Detach cameras
  27922. var canvas = this._engine.getRenderingCanvas();
  27923. if (canvas) {
  27924. var index;
  27925. for (index = 0; index < this.cameras.length; index++) {
  27926. this.cameras[index].detachControl(canvas);
  27927. }
  27928. }
  27929. // Release animation groups
  27930. while (this.animationGroups.length) {
  27931. this.animationGroups[0].dispose();
  27932. }
  27933. // Release lights
  27934. while (this.lights.length) {
  27935. this.lights[0].dispose();
  27936. }
  27937. // Release meshes
  27938. while (this.meshes.length) {
  27939. this.meshes[0].dispose(true);
  27940. }
  27941. while (this.transformNodes.length) {
  27942. this.removeTransformNode(this.transformNodes[0]);
  27943. }
  27944. // Release cameras
  27945. while (this.cameras.length) {
  27946. this.cameras[0].dispose();
  27947. }
  27948. // Release materials
  27949. if (this.defaultMaterial) {
  27950. this.defaultMaterial.dispose();
  27951. }
  27952. while (this.multiMaterials.length) {
  27953. this.multiMaterials[0].dispose();
  27954. }
  27955. while (this.materials.length) {
  27956. this.materials[0].dispose();
  27957. }
  27958. // Release particles
  27959. while (this.particleSystems.length) {
  27960. this.particleSystems[0].dispose();
  27961. }
  27962. // Release sprites
  27963. while (this.spriteManagers.length) {
  27964. this.spriteManagers[0].dispose();
  27965. }
  27966. // Release postProcesses
  27967. while (this.postProcesses.length) {
  27968. this.postProcesses[0].dispose();
  27969. }
  27970. // Release layers
  27971. while (this.layers.length) {
  27972. this.layers[0].dispose();
  27973. }
  27974. while (this.effectLayers.length) {
  27975. this.effectLayers[0].dispose();
  27976. }
  27977. // Release textures
  27978. while (this.textures.length) {
  27979. this.textures[0].dispose();
  27980. }
  27981. // Release UBO
  27982. this._sceneUbo.dispose();
  27983. if (this._alternateSceneUbo) {
  27984. this._alternateSceneUbo.dispose();
  27985. }
  27986. // Post-processes
  27987. this.postProcessManager.dispose();
  27988. if (this._postProcessRenderPipelineManager) {
  27989. this._postProcessRenderPipelineManager.dispose();
  27990. }
  27991. // Physics
  27992. if (this._physicsEngine) {
  27993. this.disablePhysicsEngine();
  27994. }
  27995. // Remove from engine
  27996. index = this._engine.scenes.indexOf(this);
  27997. if (index > -1) {
  27998. this._engine.scenes.splice(index, 1);
  27999. }
  28000. this._engine.wipeCaches(true);
  28001. this._isDisposed = true;
  28002. };
  28003. Object.defineProperty(Scene.prototype, "isDisposed", {
  28004. /**
  28005. * Gets if the scene is already disposed
  28006. */
  28007. get: function () {
  28008. return this._isDisposed;
  28009. },
  28010. enumerable: true,
  28011. configurable: true
  28012. });
  28013. /**
  28014. * Releases sounds & soundtracks
  28015. */
  28016. Scene.prototype.disposeSounds = function () {
  28017. if (!this._mainSoundTrack) {
  28018. return;
  28019. }
  28020. this.mainSoundTrack.dispose();
  28021. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28022. this.soundTracks[scIndex].dispose();
  28023. }
  28024. };
  28025. // Octrees
  28026. /**
  28027. * Get the world extend vectors with an optional filter
  28028. *
  28029. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28030. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28031. */
  28032. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28033. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28034. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28035. filterPredicate = filterPredicate || (function () { return true; });
  28036. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28037. mesh.computeWorldMatrix(true);
  28038. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28039. return;
  28040. }
  28041. var boundingInfo = mesh.getBoundingInfo();
  28042. var minBox = boundingInfo.boundingBox.minimumWorld;
  28043. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28044. BABYLON.Tools.CheckExtends(minBox, min, max);
  28045. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28046. });
  28047. return {
  28048. min: min,
  28049. max: max
  28050. };
  28051. };
  28052. /**
  28053. * Creates or updates the octree used to boost selection (picking)
  28054. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28055. * @param maxCapacity defines the maximum capacity per leaf
  28056. * @param maxDepth defines the maximum depth of the octree
  28057. * @returns an octree of AbstractMesh
  28058. */
  28059. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28060. if (maxCapacity === void 0) { maxCapacity = 64; }
  28061. if (maxDepth === void 0) { maxDepth = 2; }
  28062. if (!this._selectionOctree) {
  28063. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28064. }
  28065. var worldExtends = this.getWorldExtends();
  28066. // Update octree
  28067. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28068. return this._selectionOctree;
  28069. };
  28070. // Picking
  28071. /**
  28072. * Creates a ray that can be used to pick in the scene
  28073. * @param x defines the x coordinate of the origin (on-screen)
  28074. * @param y defines the y coordinate of the origin (on-screen)
  28075. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28076. * @param camera defines the camera to use for the picking
  28077. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28078. * @returns a Ray
  28079. */
  28080. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28081. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28082. var result = BABYLON.Ray.Zero();
  28083. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28084. return result;
  28085. };
  28086. /**
  28087. * Creates a ray that can be used to pick in the scene
  28088. * @param x defines the x coordinate of the origin (on-screen)
  28089. * @param y defines the y coordinate of the origin (on-screen)
  28090. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28091. * @param result defines the ray where to store the picking ray
  28092. * @param camera defines the camera to use for the picking
  28093. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28094. * @returns the current scene
  28095. */
  28096. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28097. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28098. var engine = this._engine;
  28099. if (!camera) {
  28100. if (!this.activeCamera)
  28101. throw new Error("Active camera not set");
  28102. camera = this.activeCamera;
  28103. }
  28104. var cameraViewport = camera.viewport;
  28105. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28106. // Moving coordinates to local viewport world
  28107. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28108. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28109. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28110. return this;
  28111. };
  28112. /**
  28113. * Creates a ray that can be used to pick in the scene
  28114. * @param x defines the x coordinate of the origin (on-screen)
  28115. * @param y defines the y coordinate of the origin (on-screen)
  28116. * @param camera defines the camera to use for the picking
  28117. * @returns a Ray
  28118. */
  28119. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28120. var result = BABYLON.Ray.Zero();
  28121. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28122. return result;
  28123. };
  28124. /**
  28125. * Creates a ray that can be used to pick in the scene
  28126. * @param x defines the x coordinate of the origin (on-screen)
  28127. * @param y defines the y coordinate of the origin (on-screen)
  28128. * @param result defines the ray where to store the picking ray
  28129. * @param camera defines the camera to use for the picking
  28130. * @returns the current scene
  28131. */
  28132. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28133. if (!BABYLON.PickingInfo) {
  28134. return this;
  28135. }
  28136. var engine = this._engine;
  28137. if (!camera) {
  28138. if (!this.activeCamera)
  28139. throw new Error("Active camera not set");
  28140. camera = this.activeCamera;
  28141. }
  28142. var cameraViewport = camera.viewport;
  28143. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28144. var identity = BABYLON.Matrix.Identity();
  28145. // Moving coordinates to local viewport world
  28146. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28147. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28148. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28149. return this;
  28150. };
  28151. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28152. if (!BABYLON.PickingInfo) {
  28153. return null;
  28154. }
  28155. var pickingInfo = null;
  28156. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28157. var mesh = this.meshes[meshIndex];
  28158. if (predicate) {
  28159. if (!predicate(mesh)) {
  28160. continue;
  28161. }
  28162. }
  28163. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28164. continue;
  28165. }
  28166. var world = mesh.getWorldMatrix();
  28167. var ray = rayFunction(world);
  28168. var result = mesh.intersects(ray, fastCheck);
  28169. if (!result || !result.hit)
  28170. continue;
  28171. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28172. continue;
  28173. pickingInfo = result;
  28174. if (fastCheck) {
  28175. break;
  28176. }
  28177. }
  28178. return pickingInfo || new BABYLON.PickingInfo();
  28179. };
  28180. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28181. if (!BABYLON.PickingInfo) {
  28182. return null;
  28183. }
  28184. var pickingInfos = new Array();
  28185. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28186. var mesh = this.meshes[meshIndex];
  28187. if (predicate) {
  28188. if (!predicate(mesh)) {
  28189. continue;
  28190. }
  28191. }
  28192. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28193. continue;
  28194. }
  28195. var world = mesh.getWorldMatrix();
  28196. var ray = rayFunction(world);
  28197. var result = mesh.intersects(ray, false);
  28198. if (!result || !result.hit)
  28199. continue;
  28200. pickingInfos.push(result);
  28201. }
  28202. return pickingInfos;
  28203. };
  28204. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28205. if (!BABYLON.PickingInfo) {
  28206. return null;
  28207. }
  28208. var pickingInfo = null;
  28209. if (!camera) {
  28210. if (!this.activeCamera) {
  28211. return null;
  28212. }
  28213. camera = this.activeCamera;
  28214. }
  28215. if (this.spriteManagers.length > 0) {
  28216. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28217. var spriteManager = this.spriteManagers[spriteIndex];
  28218. if (!spriteManager.isPickable) {
  28219. continue;
  28220. }
  28221. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28222. if (!result || !result.hit)
  28223. continue;
  28224. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28225. continue;
  28226. pickingInfo = result;
  28227. if (fastCheck) {
  28228. break;
  28229. }
  28230. }
  28231. }
  28232. return pickingInfo || new BABYLON.PickingInfo();
  28233. };
  28234. /** Launch a ray to try to pick a mesh in the scene
  28235. * @param x position on screen
  28236. * @param y position on screen
  28237. * @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
  28238. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28239. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28240. * @returns a PickingInfo
  28241. */
  28242. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28243. var _this = this;
  28244. if (!BABYLON.PickingInfo) {
  28245. return null;
  28246. }
  28247. return this._internalPick(function (world) {
  28248. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28249. return _this._tempPickingRay;
  28250. }, predicate, fastCheck);
  28251. };
  28252. /** Launch a ray to try to pick a sprite in the scene
  28253. * @param x position on screen
  28254. * @param y position on screen
  28255. * @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
  28256. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28257. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28258. * @returns a PickingInfo
  28259. */
  28260. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28261. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28262. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28263. };
  28264. /** Use the given ray to pick a mesh in the scene
  28265. * @param ray The ray to use to pick meshes
  28266. * @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
  28267. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28268. * @returns a PickingInfo
  28269. */
  28270. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28271. var _this = this;
  28272. return this._internalPick(function (world) {
  28273. if (!_this._pickWithRayInverseMatrix) {
  28274. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28275. }
  28276. world.invertToRef(_this._pickWithRayInverseMatrix);
  28277. if (!_this._cachedRayForTransform) {
  28278. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28279. }
  28280. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28281. return _this._cachedRayForTransform;
  28282. }, predicate, fastCheck);
  28283. };
  28284. /**
  28285. * Launch a ray to try to pick a mesh in the scene
  28286. * @param x X position on screen
  28287. * @param y Y position on screen
  28288. * @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
  28289. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28290. * @returns an array of PickingInfo
  28291. */
  28292. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28293. var _this = this;
  28294. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28295. };
  28296. /**
  28297. * Launch a ray to try to pick a mesh in the scene
  28298. * @param ray Ray to use
  28299. * @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
  28300. * @returns an array of PickingInfo
  28301. */
  28302. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28303. var _this = this;
  28304. return this._internalMultiPick(function (world) {
  28305. if (!_this._pickWithRayInverseMatrix) {
  28306. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28307. }
  28308. world.invertToRef(_this._pickWithRayInverseMatrix);
  28309. if (!_this._cachedRayForTransform) {
  28310. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28311. }
  28312. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28313. return _this._cachedRayForTransform;
  28314. }, predicate);
  28315. };
  28316. /**
  28317. * Force the value of meshUnderPointer
  28318. * @param mesh defines the mesh to use
  28319. */
  28320. Scene.prototype.setPointerOverMesh = function (mesh) {
  28321. if (this._pointerOverMesh === mesh) {
  28322. return;
  28323. }
  28324. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28325. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28326. }
  28327. this._pointerOverMesh = mesh;
  28328. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28329. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28330. }
  28331. };
  28332. /**
  28333. * Gets the mesh under the pointer
  28334. * @returns a Mesh or null if no mesh is under the pointer
  28335. */
  28336. Scene.prototype.getPointerOverMesh = function () {
  28337. return this._pointerOverMesh;
  28338. };
  28339. /**
  28340. * Force the sprite under the pointer
  28341. * @param sprite defines the sprite to use
  28342. */
  28343. Scene.prototype.setPointerOverSprite = function (sprite) {
  28344. if (this._pointerOverSprite === sprite) {
  28345. return;
  28346. }
  28347. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28348. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28349. }
  28350. this._pointerOverSprite = sprite;
  28351. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28352. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28353. }
  28354. };
  28355. /**
  28356. * Gets the sprite under the pointer
  28357. * @returns a Sprite or null if no sprite is under the pointer
  28358. */
  28359. Scene.prototype.getPointerOverSprite = function () {
  28360. return this._pointerOverSprite;
  28361. };
  28362. // Physics
  28363. /**
  28364. * Gets the current physics engine
  28365. * @returns a PhysicsEngine or null if none attached
  28366. */
  28367. Scene.prototype.getPhysicsEngine = function () {
  28368. return this._physicsEngine;
  28369. };
  28370. /**
  28371. * Enables physics to the current scene
  28372. * @param gravity defines the scene's gravity for the physics engine
  28373. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28374. * @return a boolean indicating if the physics engine was initialized
  28375. */
  28376. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28377. if (gravity === void 0) { gravity = null; }
  28378. if (this._physicsEngine) {
  28379. return true;
  28380. }
  28381. try {
  28382. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28383. return true;
  28384. }
  28385. catch (e) {
  28386. BABYLON.Tools.Error(e.message);
  28387. return false;
  28388. }
  28389. };
  28390. /**
  28391. * Disables and disposes the physics engine associated with the scene
  28392. */
  28393. Scene.prototype.disablePhysicsEngine = function () {
  28394. if (!this._physicsEngine) {
  28395. return;
  28396. }
  28397. this._physicsEngine.dispose();
  28398. this._physicsEngine = null;
  28399. };
  28400. /**
  28401. * Gets a boolean indicating if there is an active physics engine
  28402. * @returns a boolean indicating if there is an active physics engine
  28403. */
  28404. Scene.prototype.isPhysicsEnabled = function () {
  28405. return this._physicsEngine !== undefined;
  28406. };
  28407. /**
  28408. * Deletes a physics compound impostor
  28409. * @param compound defines the compound to delete
  28410. */
  28411. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28412. var mesh = compound.parts[0].mesh;
  28413. if (mesh.physicsImpostor) {
  28414. mesh.physicsImpostor.dispose( /*true*/);
  28415. mesh.physicsImpostor = null;
  28416. }
  28417. };
  28418. // Misc.
  28419. /** @hidden */
  28420. Scene.prototype._rebuildGeometries = function () {
  28421. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28422. var geometry = _a[_i];
  28423. geometry._rebuild();
  28424. }
  28425. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28426. var mesh = _c[_b];
  28427. mesh._rebuild();
  28428. }
  28429. if (this.postProcessManager) {
  28430. this.postProcessManager._rebuild();
  28431. }
  28432. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28433. var layer = _e[_d];
  28434. layer._rebuild();
  28435. }
  28436. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28437. var effectLayer = _g[_f];
  28438. effectLayer._rebuild();
  28439. }
  28440. if (this._boundingBoxRenderer) {
  28441. this._boundingBoxRenderer._rebuild();
  28442. }
  28443. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28444. var system = _j[_h];
  28445. system.rebuild();
  28446. }
  28447. if (this._postProcessRenderPipelineManager) {
  28448. this._postProcessRenderPipelineManager._rebuild();
  28449. }
  28450. };
  28451. /** @hidden */
  28452. Scene.prototype._rebuildTextures = function () {
  28453. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28454. var texture = _a[_i];
  28455. texture._rebuild();
  28456. }
  28457. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28458. };
  28459. /**
  28460. * Creates a default light for the scene.
  28461. * @param replace Whether to replace the existing lights in the scene.
  28462. */
  28463. Scene.prototype.createDefaultLight = function (replace) {
  28464. if (replace === void 0) { replace = false; }
  28465. // Dispose existing light in replace mode.
  28466. if (replace) {
  28467. if (this.lights) {
  28468. for (var i = 0; i < this.lights.length; i++) {
  28469. this.lights[i].dispose();
  28470. }
  28471. }
  28472. }
  28473. // Light
  28474. if (this.lights.length === 0) {
  28475. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28476. }
  28477. };
  28478. /**
  28479. * Creates a default camera for the scene.
  28480. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28481. * @param replace Whether to replace the existing active camera in the scene.
  28482. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28483. */
  28484. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28485. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28486. if (replace === void 0) { replace = false; }
  28487. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28488. // Dispose existing camera in replace mode.
  28489. if (replace) {
  28490. if (this.activeCamera) {
  28491. this.activeCamera.dispose();
  28492. this.activeCamera = null;
  28493. }
  28494. }
  28495. // Camera
  28496. if (!this.activeCamera) {
  28497. var worldExtends = this.getWorldExtends();
  28498. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28499. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28500. var camera;
  28501. var radius = worldSize.length() * 1.5;
  28502. // empty scene scenario!
  28503. if (!isFinite(radius)) {
  28504. radius = 1;
  28505. worldCenter.copyFromFloats(0, 0, 0);
  28506. }
  28507. if (createArcRotateCamera) {
  28508. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28509. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28510. arcRotateCamera.wheelPrecision = 100 / radius;
  28511. camera = arcRotateCamera;
  28512. }
  28513. else {
  28514. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28515. freeCamera.setTarget(worldCenter);
  28516. camera = freeCamera;
  28517. }
  28518. camera.minZ = radius * 0.01;
  28519. camera.maxZ = radius * 1000;
  28520. camera.speed = radius * 0.2;
  28521. this.activeCamera = camera;
  28522. var canvas = this.getEngine().getRenderingCanvas();
  28523. if (attachCameraControls && canvas) {
  28524. camera.attachControl(canvas);
  28525. }
  28526. }
  28527. };
  28528. /**
  28529. * Creates a default camera and a default light
  28530. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28531. * @param replace defines if the camera and/or light will replace the existing ones
  28532. * @param attachCameraControls defines if attachControl will be called on the new camera
  28533. */
  28534. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28535. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28536. if (replace === void 0) { replace = false; }
  28537. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28538. this.createDefaultLight(replace);
  28539. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28540. };
  28541. /**
  28542. * Creates a new sky box
  28543. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28544. * @param environmentTexture defines the texture to use as environment texture
  28545. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28546. * @param scale defines the overall scale of the skybox
  28547. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28548. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28549. * @returns a new mesh holding the sky box
  28550. */
  28551. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28552. if (pbr === void 0) { pbr = false; }
  28553. if (scale === void 0) { scale = 1000; }
  28554. if (blur === void 0) { blur = 0; }
  28555. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28556. if (!environmentTexture) {
  28557. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28558. return null;
  28559. }
  28560. if (setGlobalEnvTexture) {
  28561. if (environmentTexture) {
  28562. this.environmentTexture = environmentTexture;
  28563. }
  28564. }
  28565. // Skybox
  28566. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28567. if (pbr) {
  28568. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28569. hdrSkyboxMaterial.backFaceCulling = false;
  28570. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28571. if (hdrSkyboxMaterial.reflectionTexture) {
  28572. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28573. }
  28574. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28575. hdrSkyboxMaterial.disableLighting = true;
  28576. hdrSkyboxMaterial.twoSidedLighting = true;
  28577. hdrSkybox.infiniteDistance = true;
  28578. hdrSkybox.material = hdrSkyboxMaterial;
  28579. }
  28580. else {
  28581. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28582. skyboxMaterial.backFaceCulling = false;
  28583. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28584. if (skyboxMaterial.reflectionTexture) {
  28585. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28586. }
  28587. skyboxMaterial.disableLighting = true;
  28588. hdrSkybox.infiniteDistance = true;
  28589. hdrSkybox.material = skyboxMaterial;
  28590. }
  28591. return hdrSkybox;
  28592. };
  28593. /**
  28594. * Creates a new environment
  28595. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28596. * @param options defines the options you can use to configure the environment
  28597. * @returns the new EnvironmentHelper
  28598. */
  28599. Scene.prototype.createDefaultEnvironment = function (options) {
  28600. if (BABYLON.EnvironmentHelper) {
  28601. return new BABYLON.EnvironmentHelper(options, this);
  28602. }
  28603. return null;
  28604. };
  28605. /**
  28606. * Creates a new VREXperienceHelper
  28607. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28608. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28609. * @returns a new VREXperienceHelper
  28610. */
  28611. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28612. if (webVROptions === void 0) { webVROptions = {}; }
  28613. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28614. };
  28615. // Tags
  28616. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28617. if (tagsQuery === undefined) {
  28618. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28619. return list;
  28620. }
  28621. var listByTags = [];
  28622. forEach = forEach || (function (item) { return; });
  28623. for (var i in list) {
  28624. var item = list[i];
  28625. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28626. listByTags.push(item);
  28627. forEach(item);
  28628. }
  28629. }
  28630. return listByTags;
  28631. };
  28632. /**
  28633. * Get a list of meshes by tags
  28634. * @param tagsQuery defines the tags query to use
  28635. * @param forEach defines a predicate used to filter results
  28636. * @returns an array of Mesh
  28637. */
  28638. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28639. return this._getByTags(this.meshes, tagsQuery, forEach);
  28640. };
  28641. /**
  28642. * Get a list of cameras by tags
  28643. * @param tagsQuery defines the tags query to use
  28644. * @param forEach defines a predicate used to filter results
  28645. * @returns an array of Camera
  28646. */
  28647. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28648. return this._getByTags(this.cameras, tagsQuery, forEach);
  28649. };
  28650. /**
  28651. * Get a list of lights by tags
  28652. * @param tagsQuery defines the tags query to use
  28653. * @param forEach defines a predicate used to filter results
  28654. * @returns an array of Light
  28655. */
  28656. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28657. return this._getByTags(this.lights, tagsQuery, forEach);
  28658. };
  28659. /**
  28660. * Get a list of materials by tags
  28661. * @param tagsQuery defines the tags query to use
  28662. * @param forEach defines a predicate used to filter results
  28663. * @returns an array of Material
  28664. */
  28665. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28666. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28667. };
  28668. /**
  28669. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28670. * This allowed control for front to back rendering or reversly depending of the special needs.
  28671. *
  28672. * @param renderingGroupId The rendering group id corresponding to its index
  28673. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28674. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28675. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28676. */
  28677. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28678. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28679. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28680. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28681. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28682. };
  28683. /**
  28684. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28685. *
  28686. * @param renderingGroupId The rendering group id corresponding to its index
  28687. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28688. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28689. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28690. */
  28691. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28692. if (depth === void 0) { depth = true; }
  28693. if (stencil === void 0) { stencil = true; }
  28694. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28695. };
  28696. /**
  28697. * Will flag all materials as dirty to trigger new shader compilation
  28698. * @param flag defines the flag used to specify which material part must be marked as dirty
  28699. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28700. */
  28701. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28702. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28703. var material = _a[_i];
  28704. if (predicate && !predicate(material)) {
  28705. continue;
  28706. }
  28707. material.markAsDirty(flag);
  28708. }
  28709. };
  28710. /** @hidden */
  28711. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28712. var _this = this;
  28713. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28714. this._activeRequests.push(request);
  28715. request.onCompleteObservable.add(function (request) {
  28716. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28717. });
  28718. return request;
  28719. };
  28720. /** @hidden */
  28721. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28722. var _this = this;
  28723. return new Promise(function (resolve, reject) {
  28724. _this._loadFile(url, function (data) {
  28725. resolve(data);
  28726. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28727. reject(exception);
  28728. });
  28729. });
  28730. };
  28731. // Statics
  28732. Scene._FOGMODE_NONE = 0;
  28733. Scene._FOGMODE_EXP = 1;
  28734. Scene._FOGMODE_EXP2 = 2;
  28735. Scene._FOGMODE_LINEAR = 3;
  28736. Scene._uniqueIdCounter = 0;
  28737. /**
  28738. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28739. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28740. */
  28741. Scene.MinDeltaTime = 1.0;
  28742. /**
  28743. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28744. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28745. */
  28746. Scene.MaxDeltaTime = 1000.0;
  28747. /** The distance in pixel that you have to move to prevent some events */
  28748. Scene.DragMovementThreshold = 10; // in pixels
  28749. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28750. Scene.LongPressDelay = 500; // in milliseconds
  28751. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28752. Scene.DoubleClickDelay = 300; // in milliseconds
  28753. /** If you need to check double click without raising a single click at first click, enable this flag */
  28754. Scene.ExclusiveDoubleClickMode = false;
  28755. return Scene;
  28756. }());
  28757. BABYLON.Scene = Scene;
  28758. })(BABYLON || (BABYLON = {}));
  28759. //# sourceMappingURL=babylon.scene.js.map
  28760. var BABYLON;
  28761. (function (BABYLON) {
  28762. /**
  28763. * Set of assets to keep when moving a scene into an asset container.
  28764. */
  28765. var KeepAssets = /** @class */ (function () {
  28766. function KeepAssets() {
  28767. /**
  28768. * Cameras to keep.
  28769. */
  28770. this.cameras = new Array();
  28771. /**
  28772. * Lights to keep.
  28773. */
  28774. this.lights = new Array();
  28775. /**
  28776. * Meshes to keep.
  28777. */
  28778. this.meshes = new Array();
  28779. /**
  28780. * Skeletons to keep.
  28781. */
  28782. this.skeletons = new Array();
  28783. /**
  28784. * ParticleSystems to keep.
  28785. */
  28786. this.particleSystems = new Array();
  28787. /**
  28788. * Animations to keep.
  28789. */
  28790. this.animations = new Array();
  28791. /**
  28792. * AnimationGroups to keep.
  28793. */
  28794. this.animationGroups = new Array();
  28795. /**
  28796. * MultiMaterials to keep.
  28797. */
  28798. this.multiMaterials = new Array();
  28799. /**
  28800. * Materials to keep.
  28801. */
  28802. this.materials = new Array();
  28803. /**
  28804. * MorphTargetManagers to keep.
  28805. */
  28806. this.morphTargetManagers = new Array();
  28807. /**
  28808. * Geometries to keep.
  28809. */
  28810. this.geometries = new Array();
  28811. /**
  28812. * TransformNodes to keep.
  28813. */
  28814. this.transformNodes = new Array();
  28815. /**
  28816. * LensFlareSystems to keep.
  28817. */
  28818. this.lensFlareSystems = new Array();
  28819. /**
  28820. * ShadowGenerators to keep.
  28821. */
  28822. this.shadowGenerators = new Array();
  28823. /**
  28824. * ActionManagers to keep.
  28825. */
  28826. this.actionManagers = new Array();
  28827. /**
  28828. * Sounds to keep.
  28829. */
  28830. this.sounds = new Array();
  28831. /**
  28832. * Textures to keep.
  28833. */
  28834. this.textures = new Array();
  28835. /**
  28836. * Effect layers to keep.
  28837. */
  28838. this.effectLayers = new Array();
  28839. }
  28840. return KeepAssets;
  28841. }());
  28842. BABYLON.KeepAssets = KeepAssets;
  28843. /**
  28844. * Container with a set of assets that can be added or removed from a scene.
  28845. */
  28846. var AssetContainer = /** @class */ (function () {
  28847. /**
  28848. * Instantiates an AssetContainer.
  28849. * @param scene The scene the AssetContainer belongs to.
  28850. */
  28851. function AssetContainer(scene) {
  28852. // Objects
  28853. /**
  28854. * Cameras populated in the container.
  28855. */
  28856. this.cameras = new Array();
  28857. /**
  28858. * Lights populated in the container.
  28859. */
  28860. this.lights = new Array();
  28861. /**
  28862. * Meshes populated in the container.
  28863. */
  28864. this.meshes = new Array();
  28865. /**
  28866. * Skeletons populated in the container.
  28867. */
  28868. this.skeletons = new Array();
  28869. /**
  28870. * ParticleSystems populated in the container.
  28871. */
  28872. this.particleSystems = new Array();
  28873. /**
  28874. * Animations populated in the container.
  28875. */
  28876. this.animations = new Array();
  28877. /**
  28878. * AnimationGroups populated in the container.
  28879. */
  28880. this.animationGroups = new Array();
  28881. /**
  28882. * MultiMaterials populated in the container.
  28883. */
  28884. this.multiMaterials = new Array();
  28885. /**
  28886. * Materials populated in the container.
  28887. */
  28888. this.materials = new Array();
  28889. /**
  28890. * MorphTargetManagers populated in the container.
  28891. */
  28892. this.morphTargetManagers = new Array();
  28893. /**
  28894. * Geometries populated in the container.
  28895. */
  28896. this.geometries = new Array();
  28897. /**
  28898. * TransformNodes populated in the container.
  28899. */
  28900. this.transformNodes = new Array();
  28901. /**
  28902. * LensFlareSystems populated in the container.
  28903. */
  28904. this.lensFlareSystems = new Array();
  28905. /**
  28906. * ShadowGenerators populated in the container.
  28907. */
  28908. this.shadowGenerators = new Array();
  28909. /**
  28910. * ActionManagers populated in the container.
  28911. */
  28912. this.actionManagers = new Array();
  28913. /**
  28914. * Sounds populated in the container.
  28915. */
  28916. this.sounds = new Array();
  28917. /**
  28918. * Textures populated in the container.
  28919. */
  28920. this.textures = new Array();
  28921. /**
  28922. * Effect layers populated in the container.
  28923. */
  28924. this.effectLayers = new Array();
  28925. this.scene = scene;
  28926. }
  28927. /**
  28928. * Adds all the assets from the container to the scene.
  28929. */
  28930. AssetContainer.prototype.addAllToScene = function () {
  28931. var _this = this;
  28932. this.cameras.forEach(function (o) {
  28933. _this.scene.addCamera(o);
  28934. });
  28935. this.lights.forEach(function (o) {
  28936. _this.scene.addLight(o);
  28937. });
  28938. this.meshes.forEach(function (o) {
  28939. _this.scene.addMesh(o);
  28940. });
  28941. this.skeletons.forEach(function (o) {
  28942. _this.scene.addSkeleton(o);
  28943. });
  28944. this.particleSystems.forEach(function (o) {
  28945. _this.scene.addParticleSystem(o);
  28946. });
  28947. this.animations.forEach(function (o) {
  28948. _this.scene.addAnimation(o);
  28949. });
  28950. this.animationGroups.forEach(function (o) {
  28951. _this.scene.addAnimationGroup(o);
  28952. });
  28953. this.multiMaterials.forEach(function (o) {
  28954. _this.scene.addMultiMaterial(o);
  28955. });
  28956. this.materials.forEach(function (o) {
  28957. _this.scene.addMaterial(o);
  28958. });
  28959. this.morphTargetManagers.forEach(function (o) {
  28960. _this.scene.addMorphTargetManager(o);
  28961. });
  28962. this.geometries.forEach(function (o) {
  28963. _this.scene.addGeometry(o);
  28964. });
  28965. this.transformNodes.forEach(function (o) {
  28966. _this.scene.addTransformNode(o);
  28967. });
  28968. this.lensFlareSystems.forEach(function (o) {
  28969. _this.scene.addLensFlareSystem(o);
  28970. });
  28971. this.actionManagers.forEach(function (o) {
  28972. _this.scene.addActionManager(o);
  28973. });
  28974. this.sounds.forEach(function (o) {
  28975. o.play();
  28976. o.autoplay = true;
  28977. _this.scene.mainSoundTrack.AddSound(o);
  28978. });
  28979. this.textures.forEach(function (o) {
  28980. _this.scene.addTexture(o);
  28981. });
  28982. this.effectLayers.forEach(function (o) {
  28983. _this.scene.addEffectLayer(o);
  28984. });
  28985. };
  28986. /**
  28987. * Removes all the assets in the container from the scene
  28988. */
  28989. AssetContainer.prototype.removeAllFromScene = function () {
  28990. var _this = this;
  28991. this.cameras.forEach(function (o) {
  28992. _this.scene.removeCamera(o);
  28993. });
  28994. this.lights.forEach(function (o) {
  28995. _this.scene.removeLight(o);
  28996. });
  28997. this.meshes.forEach(function (o) {
  28998. _this.scene.removeMesh(o);
  28999. });
  29000. this.skeletons.forEach(function (o) {
  29001. _this.scene.removeSkeleton(o);
  29002. });
  29003. this.particleSystems.forEach(function (o) {
  29004. _this.scene.removeParticleSystem(o);
  29005. });
  29006. this.animations.forEach(function (o) {
  29007. _this.scene.removeAnimation(o);
  29008. });
  29009. this.animationGroups.forEach(function (o) {
  29010. _this.scene.removeAnimationGroup(o);
  29011. });
  29012. this.multiMaterials.forEach(function (o) {
  29013. _this.scene.removeMultiMaterial(o);
  29014. });
  29015. this.materials.forEach(function (o) {
  29016. _this.scene.removeMaterial(o);
  29017. });
  29018. this.morphTargetManagers.forEach(function (o) {
  29019. _this.scene.removeMorphTargetManager(o);
  29020. });
  29021. this.geometries.forEach(function (o) {
  29022. _this.scene.removeGeometry(o);
  29023. });
  29024. this.transformNodes.forEach(function (o) {
  29025. _this.scene.removeTransformNode(o);
  29026. });
  29027. this.lensFlareSystems.forEach(function (o) {
  29028. _this.scene.removeLensFlareSystem(o);
  29029. });
  29030. this.actionManagers.forEach(function (o) {
  29031. _this.scene.removeActionManager(o);
  29032. });
  29033. this.sounds.forEach(function (o) {
  29034. o.stop();
  29035. o.autoplay = false;
  29036. _this.scene.mainSoundTrack.RemoveSound(o);
  29037. });
  29038. this.textures.forEach(function (o) {
  29039. _this.scene.removeTexture(o);
  29040. });
  29041. this.effectLayers.forEach(function (o) {
  29042. _this.scene.removeEffectLayer(o);
  29043. });
  29044. };
  29045. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29046. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29047. var asset = sourceAssets_1[_i];
  29048. var move = true;
  29049. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29050. var keepAsset = keepAssets_1[_a];
  29051. if (asset === keepAsset) {
  29052. move = false;
  29053. break;
  29054. }
  29055. }
  29056. if (move) {
  29057. targetAssets.push(asset);
  29058. }
  29059. }
  29060. };
  29061. /**
  29062. * Removes all the assets contained in the scene and adds them to the container.
  29063. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29064. */
  29065. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29066. if (keepAssets === undefined) {
  29067. keepAssets = new KeepAssets();
  29068. }
  29069. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29070. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29071. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29072. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29073. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29074. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29075. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29076. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29077. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29078. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29079. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29080. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29081. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29082. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29083. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29084. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29085. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29086. this.removeAllFromScene();
  29087. };
  29088. return AssetContainer;
  29089. }());
  29090. BABYLON.AssetContainer = AssetContainer;
  29091. })(BABYLON || (BABYLON = {}));
  29092. //# sourceMappingURL=babylon.assetContainer.js.map
  29093. var BABYLON;
  29094. (function (BABYLON) {
  29095. var Buffer = /** @class */ (function () {
  29096. /**
  29097. * Constructor
  29098. * @param engine the engine
  29099. * @param data the data to use for this buffer
  29100. * @param updatable whether the data is updatable
  29101. * @param stride the stride (optional)
  29102. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29103. * @param instanced whether the buffer is instanced (optional)
  29104. * @param useBytes set to true if the stride in in bytes (optional)
  29105. */
  29106. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29107. if (stride === void 0) { stride = 0; }
  29108. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29109. if (instanced === void 0) { instanced = false; }
  29110. if (useBytes === void 0) { useBytes = false; }
  29111. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29112. this._engine = engine.getScene().getEngine();
  29113. }
  29114. else {
  29115. this._engine = engine;
  29116. }
  29117. this._updatable = updatable;
  29118. this._instanced = instanced;
  29119. this._data = data;
  29120. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29121. if (!postponeInternalCreation) { // by default
  29122. this.create();
  29123. }
  29124. }
  29125. /**
  29126. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29127. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29128. * @param offset defines offset in the buffer (0 by default)
  29129. * @param size defines the size in floats of attributes (position is 3 for instance)
  29130. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29131. * @param instanced defines if the vertex buffer contains indexed data
  29132. * @param useBytes defines if the offset and stride are in bytes
  29133. * @returns the new vertex buffer
  29134. */
  29135. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29136. if (useBytes === void 0) { useBytes = false; }
  29137. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29138. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29139. // a lot of these parameters are ignored as they are overriden by the buffer
  29140. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29141. };
  29142. // Properties
  29143. Buffer.prototype.isUpdatable = function () {
  29144. return this._updatable;
  29145. };
  29146. Buffer.prototype.getData = function () {
  29147. return this._data;
  29148. };
  29149. Buffer.prototype.getBuffer = function () {
  29150. return this._buffer;
  29151. };
  29152. /**
  29153. * Gets the stride in float32 units (i.e. byte stride / 4).
  29154. * May not be an integer if the byte stride is not divisible by 4.
  29155. * DEPRECATED. Use byteStride instead.
  29156. * @returns the stride in float32 units
  29157. */
  29158. Buffer.prototype.getStrideSize = function () {
  29159. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29160. };
  29161. // Methods
  29162. Buffer.prototype.create = function (data) {
  29163. if (data === void 0) { data = null; }
  29164. if (!data && this._buffer) {
  29165. return; // nothing to do
  29166. }
  29167. data = data || this._data;
  29168. if (!data) {
  29169. return;
  29170. }
  29171. if (!this._buffer) { // create buffer
  29172. if (this._updatable) {
  29173. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29174. this._data = data;
  29175. }
  29176. else {
  29177. this._buffer = this._engine.createVertexBuffer(data);
  29178. }
  29179. }
  29180. else if (this._updatable) { // update buffer
  29181. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29182. this._data = data;
  29183. }
  29184. };
  29185. Buffer.prototype._rebuild = function () {
  29186. this._buffer = null;
  29187. this.create(this._data);
  29188. };
  29189. Buffer.prototype.update = function (data) {
  29190. this.create(data);
  29191. };
  29192. /**
  29193. * Updates the data directly.
  29194. * @param data the new data
  29195. * @param offset the new offset
  29196. * @param vertexCount the vertex count (optional)
  29197. * @param useBytes set to true if the offset is in bytes
  29198. */
  29199. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29200. if (useBytes === void 0) { useBytes = false; }
  29201. if (!this._buffer) {
  29202. return;
  29203. }
  29204. if (this._updatable) { // update buffer
  29205. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29206. this._data = null;
  29207. }
  29208. };
  29209. Buffer.prototype.dispose = function () {
  29210. if (!this._buffer) {
  29211. return;
  29212. }
  29213. if (this._engine._releaseBuffer(this._buffer)) {
  29214. this._buffer = null;
  29215. }
  29216. };
  29217. return Buffer;
  29218. }());
  29219. BABYLON.Buffer = Buffer;
  29220. })(BABYLON || (BABYLON = {}));
  29221. //# sourceMappingURL=babylon.buffer.js.map
  29222. var BABYLON;
  29223. (function (BABYLON) {
  29224. var VertexBuffer = /** @class */ (function () {
  29225. /**
  29226. * Constructor
  29227. * @param engine the engine
  29228. * @param data the data to use for this vertex buffer
  29229. * @param kind the vertex buffer kind
  29230. * @param updatable whether the data is updatable
  29231. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29232. * @param stride the stride (optional)
  29233. * @param instanced whether the buffer is instanced (optional)
  29234. * @param offset the offset of the data (optional)
  29235. * @param size the number of components (optional)
  29236. * @param type the type of the component (optional)
  29237. * @param normalized whether the data contains normalized data (optional)
  29238. * @param useBytes set to true if stride and offset are in bytes (optional)
  29239. */
  29240. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29241. if (normalized === void 0) { normalized = false; }
  29242. if (useBytes === void 0) { useBytes = false; }
  29243. if (data instanceof BABYLON.Buffer) {
  29244. this._buffer = data;
  29245. this._ownsBuffer = false;
  29246. }
  29247. else {
  29248. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29249. this._ownsBuffer = true;
  29250. }
  29251. this._kind = kind;
  29252. if (type == undefined) {
  29253. var data_1 = this.getData();
  29254. this.type = VertexBuffer.FLOAT;
  29255. if (data_1 instanceof Int8Array)
  29256. this.type = VertexBuffer.BYTE;
  29257. else if (data_1 instanceof Uint8Array)
  29258. this.type = VertexBuffer.UNSIGNED_BYTE;
  29259. else if (data_1 instanceof Int16Array)
  29260. this.type = VertexBuffer.SHORT;
  29261. else if (data_1 instanceof Uint16Array)
  29262. this.type = VertexBuffer.UNSIGNED_SHORT;
  29263. else if (data_1 instanceof Int32Array)
  29264. this.type = VertexBuffer.INT;
  29265. else if (data_1 instanceof Uint32Array)
  29266. this.type = VertexBuffer.UNSIGNED_INT;
  29267. }
  29268. else {
  29269. this.type = type;
  29270. }
  29271. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29272. if (useBytes) {
  29273. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29274. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29275. this.byteOffset = offset || 0;
  29276. }
  29277. else {
  29278. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29279. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29280. this.byteOffset = (offset || 0) * typeByteLength;
  29281. }
  29282. this.normalized = normalized;
  29283. this._instanced = instanced !== undefined ? instanced : false;
  29284. this._instanceDivisor = instanced ? 1 : 0;
  29285. }
  29286. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29287. /**
  29288. * Gets or sets the instance divisor when in instanced mode
  29289. */
  29290. get: function () {
  29291. return this._instanceDivisor;
  29292. },
  29293. set: function (value) {
  29294. this._instanceDivisor = value;
  29295. if (value == 0) {
  29296. this._instanced = false;
  29297. }
  29298. else {
  29299. this._instanced = true;
  29300. }
  29301. },
  29302. enumerable: true,
  29303. configurable: true
  29304. });
  29305. VertexBuffer.prototype._rebuild = function () {
  29306. if (!this._buffer) {
  29307. return;
  29308. }
  29309. this._buffer._rebuild();
  29310. };
  29311. /**
  29312. * Returns the kind of the VertexBuffer (string).
  29313. */
  29314. VertexBuffer.prototype.getKind = function () {
  29315. return this._kind;
  29316. };
  29317. // Properties
  29318. /**
  29319. * Boolean : is the VertexBuffer updatable ?
  29320. */
  29321. VertexBuffer.prototype.isUpdatable = function () {
  29322. return this._buffer.isUpdatable();
  29323. };
  29324. /**
  29325. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29326. */
  29327. VertexBuffer.prototype.getData = function () {
  29328. return this._buffer.getData();
  29329. };
  29330. /**
  29331. * Returns the WebGLBuffer associated to the VertexBuffer.
  29332. */
  29333. VertexBuffer.prototype.getBuffer = function () {
  29334. return this._buffer.getBuffer();
  29335. };
  29336. /**
  29337. * Returns the stride as a multiple of the type byte length.
  29338. * DEPRECATED. Use byteStride instead.
  29339. */
  29340. VertexBuffer.prototype.getStrideSize = function () {
  29341. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29342. };
  29343. /**
  29344. * Returns the offset as a multiple of the type byte length.
  29345. * DEPRECATED. Use byteOffset instead.
  29346. */
  29347. VertexBuffer.prototype.getOffset = function () {
  29348. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29349. };
  29350. /**
  29351. * Returns the number of components per vertex attribute (integer).
  29352. */
  29353. VertexBuffer.prototype.getSize = function () {
  29354. return this._size;
  29355. };
  29356. /**
  29357. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29358. */
  29359. VertexBuffer.prototype.getIsInstanced = function () {
  29360. return this._instanced;
  29361. };
  29362. /**
  29363. * Returns the instancing divisor, zero for non-instanced (integer).
  29364. */
  29365. VertexBuffer.prototype.getInstanceDivisor = function () {
  29366. return this._instanceDivisor;
  29367. };
  29368. // Methods
  29369. /**
  29370. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29371. * Returns the created WebGLBuffer.
  29372. */
  29373. VertexBuffer.prototype.create = function (data) {
  29374. return this._buffer.create(data);
  29375. };
  29376. /**
  29377. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29378. * This function will create a new buffer if the current one is not updatable
  29379. * Returns the updated WebGLBuffer.
  29380. */
  29381. VertexBuffer.prototype.update = function (data) {
  29382. return this._buffer.update(data);
  29383. };
  29384. /**
  29385. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29386. * Returns the directly updated WebGLBuffer.
  29387. * @param data the new data
  29388. * @param offset the new offset
  29389. * @param useBytes set to true if the offset is in bytes
  29390. */
  29391. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29392. if (useBytes === void 0) { useBytes = false; }
  29393. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29394. };
  29395. /**
  29396. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29397. */
  29398. VertexBuffer.prototype.dispose = function () {
  29399. if (this._ownsBuffer) {
  29400. this._buffer.dispose();
  29401. }
  29402. };
  29403. /**
  29404. * Enumerates each value of this vertex buffer as numbers.
  29405. * @param count the number of values to enumerate
  29406. * @param callback the callback function called for each value
  29407. */
  29408. VertexBuffer.prototype.forEach = function (count, callback) {
  29409. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29410. };
  29411. Object.defineProperty(VertexBuffer, "PositionKind", {
  29412. get: function () {
  29413. return VertexBuffer._PositionKind;
  29414. },
  29415. enumerable: true,
  29416. configurable: true
  29417. });
  29418. Object.defineProperty(VertexBuffer, "NormalKind", {
  29419. get: function () {
  29420. return VertexBuffer._NormalKind;
  29421. },
  29422. enumerable: true,
  29423. configurable: true
  29424. });
  29425. Object.defineProperty(VertexBuffer, "TangentKind", {
  29426. get: function () {
  29427. return VertexBuffer._TangentKind;
  29428. },
  29429. enumerable: true,
  29430. configurable: true
  29431. });
  29432. Object.defineProperty(VertexBuffer, "UVKind", {
  29433. get: function () {
  29434. return VertexBuffer._UVKind;
  29435. },
  29436. enumerable: true,
  29437. configurable: true
  29438. });
  29439. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29440. get: function () {
  29441. return VertexBuffer._UV2Kind;
  29442. },
  29443. enumerable: true,
  29444. configurable: true
  29445. });
  29446. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29447. get: function () {
  29448. return VertexBuffer._UV3Kind;
  29449. },
  29450. enumerable: true,
  29451. configurable: true
  29452. });
  29453. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29454. get: function () {
  29455. return VertexBuffer._UV4Kind;
  29456. },
  29457. enumerable: true,
  29458. configurable: true
  29459. });
  29460. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29461. get: function () {
  29462. return VertexBuffer._UV5Kind;
  29463. },
  29464. enumerable: true,
  29465. configurable: true
  29466. });
  29467. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29468. get: function () {
  29469. return VertexBuffer._UV6Kind;
  29470. },
  29471. enumerable: true,
  29472. configurable: true
  29473. });
  29474. Object.defineProperty(VertexBuffer, "ColorKind", {
  29475. get: function () {
  29476. return VertexBuffer._ColorKind;
  29477. },
  29478. enumerable: true,
  29479. configurable: true
  29480. });
  29481. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29482. get: function () {
  29483. return VertexBuffer._MatricesIndicesKind;
  29484. },
  29485. enumerable: true,
  29486. configurable: true
  29487. });
  29488. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29489. get: function () {
  29490. return VertexBuffer._MatricesWeightsKind;
  29491. },
  29492. enumerable: true,
  29493. configurable: true
  29494. });
  29495. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29496. get: function () {
  29497. return VertexBuffer._MatricesIndicesExtraKind;
  29498. },
  29499. enumerable: true,
  29500. configurable: true
  29501. });
  29502. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29503. get: function () {
  29504. return VertexBuffer._MatricesWeightsExtraKind;
  29505. },
  29506. enumerable: true,
  29507. configurable: true
  29508. });
  29509. /**
  29510. * Deduces the stride given a kind.
  29511. * @param kind The kind string to deduce
  29512. * @returns The deduced stride
  29513. */
  29514. VertexBuffer.DeduceStride = function (kind) {
  29515. switch (kind) {
  29516. case VertexBuffer.UVKind:
  29517. case VertexBuffer.UV2Kind:
  29518. case VertexBuffer.UV3Kind:
  29519. case VertexBuffer.UV4Kind:
  29520. case VertexBuffer.UV5Kind:
  29521. case VertexBuffer.UV6Kind:
  29522. return 2;
  29523. case VertexBuffer.NormalKind:
  29524. case VertexBuffer.PositionKind:
  29525. return 3;
  29526. case VertexBuffer.ColorKind:
  29527. case VertexBuffer.MatricesIndicesKind:
  29528. case VertexBuffer.MatricesIndicesExtraKind:
  29529. case VertexBuffer.MatricesWeightsKind:
  29530. case VertexBuffer.MatricesWeightsExtraKind:
  29531. case VertexBuffer.TangentKind:
  29532. return 4;
  29533. default:
  29534. throw new Error("Invalid kind '" + kind + "'");
  29535. }
  29536. };
  29537. /**
  29538. * Gets the byte length of the given type.
  29539. * @param type the type
  29540. * @returns the number of bytes
  29541. */
  29542. VertexBuffer.GetTypeByteLength = function (type) {
  29543. switch (type) {
  29544. case VertexBuffer.BYTE:
  29545. case VertexBuffer.UNSIGNED_BYTE:
  29546. return 1;
  29547. case VertexBuffer.SHORT:
  29548. case VertexBuffer.UNSIGNED_SHORT:
  29549. return 2;
  29550. case VertexBuffer.INT:
  29551. case VertexBuffer.FLOAT:
  29552. return 4;
  29553. default:
  29554. throw new Error("Invalid type '" + type + "'");
  29555. }
  29556. };
  29557. /**
  29558. * Enumerates each value of the given parameters as numbers.
  29559. * @param data the data to enumerate
  29560. * @param byteOffset the byte offset of the data
  29561. * @param byteStride the byte stride of the data
  29562. * @param componentCount the number of components per element
  29563. * @param componentType the type of the component
  29564. * @param count the total number of components
  29565. * @param normalized whether the data is normalized
  29566. * @param callback the callback function called for each value
  29567. */
  29568. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29569. if (data instanceof Array) {
  29570. var offset = byteOffset / 4;
  29571. var stride = byteStride / 4;
  29572. for (var index = 0; index < count; index += componentCount) {
  29573. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29574. callback(data[offset + componentIndex], index + componentIndex);
  29575. }
  29576. offset += stride;
  29577. }
  29578. }
  29579. else {
  29580. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29581. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29582. for (var index = 0; index < count; index += componentCount) {
  29583. var componentByteOffset = byteOffset;
  29584. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29585. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29586. callback(value, index + componentIndex);
  29587. componentByteOffset += componentByteLength;
  29588. }
  29589. byteOffset += byteStride;
  29590. }
  29591. }
  29592. };
  29593. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29594. switch (type) {
  29595. case VertexBuffer.BYTE: {
  29596. var value = dataView.getInt8(byteOffset);
  29597. if (normalized) {
  29598. value = Math.max(value / 127, -1);
  29599. }
  29600. return value;
  29601. }
  29602. case VertexBuffer.UNSIGNED_BYTE: {
  29603. var value = dataView.getUint8(byteOffset);
  29604. if (normalized) {
  29605. value = value / 255;
  29606. }
  29607. return value;
  29608. }
  29609. case VertexBuffer.SHORT: {
  29610. var value = dataView.getInt16(byteOffset, true);
  29611. if (normalized) {
  29612. value = Math.max(value / 16383, -1);
  29613. }
  29614. return value;
  29615. }
  29616. case VertexBuffer.UNSIGNED_SHORT: {
  29617. var value = dataView.getUint16(byteOffset, true);
  29618. if (normalized) {
  29619. value = value / 65535;
  29620. }
  29621. return value;
  29622. }
  29623. case VertexBuffer.FLOAT: {
  29624. return dataView.getFloat32(byteOffset, true);
  29625. }
  29626. default: {
  29627. throw new Error("Invalid component type " + type);
  29628. }
  29629. }
  29630. };
  29631. /**
  29632. * The byte type.
  29633. */
  29634. VertexBuffer.BYTE = 5120;
  29635. /**
  29636. * The unsigned byte type.
  29637. */
  29638. VertexBuffer.UNSIGNED_BYTE = 5121;
  29639. /**
  29640. * The short type.
  29641. */
  29642. VertexBuffer.SHORT = 5122;
  29643. /**
  29644. * The unsigned short type.
  29645. */
  29646. VertexBuffer.UNSIGNED_SHORT = 5123;
  29647. /**
  29648. * The integer type.
  29649. */
  29650. VertexBuffer.INT = 5124;
  29651. /**
  29652. * The unsigned integer type.
  29653. */
  29654. VertexBuffer.UNSIGNED_INT = 5125;
  29655. /**
  29656. * The float type.
  29657. */
  29658. VertexBuffer.FLOAT = 5126;
  29659. // Enums
  29660. VertexBuffer._PositionKind = "position";
  29661. VertexBuffer._NormalKind = "normal";
  29662. VertexBuffer._TangentKind = "tangent";
  29663. VertexBuffer._UVKind = "uv";
  29664. VertexBuffer._UV2Kind = "uv2";
  29665. VertexBuffer._UV3Kind = "uv3";
  29666. VertexBuffer._UV4Kind = "uv4";
  29667. VertexBuffer._UV5Kind = "uv5";
  29668. VertexBuffer._UV6Kind = "uv6";
  29669. VertexBuffer._ColorKind = "color";
  29670. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29671. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29672. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29673. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29674. return VertexBuffer;
  29675. }());
  29676. BABYLON.VertexBuffer = VertexBuffer;
  29677. })(BABYLON || (BABYLON = {}));
  29678. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29679. var BABYLON;
  29680. (function (BABYLON) {
  29681. /**
  29682. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29683. */
  29684. var DummyInternalTextureTracker = /** @class */ (function () {
  29685. function DummyInternalTextureTracker() {
  29686. /**
  29687. * Gets or set the previous tracker in the list
  29688. */
  29689. this.previous = null;
  29690. /**
  29691. * Gets or set the next tracker in the list
  29692. */
  29693. this.next = null;
  29694. }
  29695. return DummyInternalTextureTracker;
  29696. }());
  29697. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29698. })(BABYLON || (BABYLON = {}));
  29699. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29700. var BABYLON;
  29701. (function (BABYLON) {
  29702. /**
  29703. * Class used to store data associated with WebGL texture data for the engine
  29704. * This class should not be used directly
  29705. */
  29706. var InternalTexture = /** @class */ (function () {
  29707. /**
  29708. * Creates a new InternalTexture
  29709. * @param engine defines the engine to use
  29710. * @param dataSource defines the type of data that will be used
  29711. */
  29712. function InternalTexture(engine, dataSource) {
  29713. /**
  29714. * Observable called when the texture is loaded
  29715. */
  29716. this.onLoadedObservable = new BABYLON.Observable();
  29717. /**
  29718. * Gets or set the previous tracker in the list
  29719. */
  29720. this.previous = null;
  29721. /**
  29722. * Gets or set the next tracker in the list
  29723. */
  29724. this.next = null;
  29725. // Private
  29726. /** @hidden */
  29727. this._initialSlot = -1;
  29728. /** @hidden */
  29729. this._designatedSlot = -1;
  29730. /** @hidden */
  29731. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29732. /** @hidden */
  29733. this._comparisonFunction = 0;
  29734. /** @hidden */
  29735. this._references = 1;
  29736. this._engine = engine;
  29737. this._dataSource = dataSource;
  29738. this._webGLTexture = engine._createTexture();
  29739. }
  29740. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29741. /**
  29742. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29743. */
  29744. get: function () {
  29745. return this._dataSource;
  29746. },
  29747. enumerable: true,
  29748. configurable: true
  29749. });
  29750. /**
  29751. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29752. */
  29753. InternalTexture.prototype.incrementReferences = function () {
  29754. this._references++;
  29755. };
  29756. /**
  29757. * Change the size of the texture (not the size of the content)
  29758. * @param width defines the new width
  29759. * @param height defines the new height
  29760. * @param depth defines the new depth (1 by default)
  29761. */
  29762. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29763. if (depth === void 0) { depth = 1; }
  29764. this.width = width;
  29765. this.height = height;
  29766. this.depth = depth;
  29767. this.baseWidth = width;
  29768. this.baseHeight = height;
  29769. this.baseDepth = depth;
  29770. this._size = width * height * depth;
  29771. };
  29772. /** @hidden */
  29773. InternalTexture.prototype._rebuild = function () {
  29774. var _this = this;
  29775. var proxy;
  29776. this.isReady = false;
  29777. this._cachedCoordinatesMode = null;
  29778. this._cachedWrapU = null;
  29779. this._cachedWrapV = null;
  29780. this._cachedAnisotropicFilteringLevel = null;
  29781. switch (this._dataSource) {
  29782. case InternalTexture.DATASOURCE_TEMP:
  29783. return;
  29784. case InternalTexture.DATASOURCE_URL:
  29785. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29786. _this.isReady = true;
  29787. }, null, this._buffer, undefined, this.format);
  29788. proxy._swapAndDie(this);
  29789. return;
  29790. case InternalTexture.DATASOURCE_RAW:
  29791. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29792. proxy._swapAndDie(this);
  29793. this.isReady = true;
  29794. return;
  29795. case InternalTexture.DATASOURCE_RAW3D:
  29796. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29797. proxy._swapAndDie(this);
  29798. this.isReady = true;
  29799. return;
  29800. case InternalTexture.DATASOURCE_DYNAMIC:
  29801. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29802. proxy._swapAndDie(this);
  29803. // The engine will make sure to update content so no need to flag it as isReady = true
  29804. return;
  29805. case InternalTexture.DATASOURCE_RENDERTARGET:
  29806. var options = new BABYLON.RenderTargetCreationOptions();
  29807. options.generateDepthBuffer = this._generateDepthBuffer;
  29808. options.generateMipMaps = this.generateMipMaps;
  29809. options.generateStencilBuffer = this._generateStencilBuffer;
  29810. options.samplingMode = this.samplingMode;
  29811. options.type = this.type;
  29812. if (this.isCube) {
  29813. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29814. }
  29815. else {
  29816. var size = {
  29817. width: this.width,
  29818. height: this.height
  29819. };
  29820. proxy = this._engine.createRenderTargetTexture(size, options);
  29821. }
  29822. proxy._swapAndDie(this);
  29823. this.isReady = true;
  29824. return;
  29825. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29826. var depthTextureOptions = {
  29827. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29828. comparisonFunction: this._comparisonFunction,
  29829. generateStencil: this._generateStencilBuffer,
  29830. isCube: this.isCube
  29831. };
  29832. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29833. proxy._swapAndDie(this);
  29834. this.isReady = true;
  29835. return;
  29836. case InternalTexture.DATASOURCE_CUBE:
  29837. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29838. _this.isReady = true;
  29839. }, null, this.format, this._extension);
  29840. proxy._swapAndDie(this);
  29841. return;
  29842. case InternalTexture.DATASOURCE_CUBERAW:
  29843. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29844. proxy._swapAndDie(this);
  29845. this.isReady = true;
  29846. return;
  29847. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29848. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29849. if (proxy) {
  29850. proxy._swapAndDie(_this);
  29851. }
  29852. _this.isReady = true;
  29853. }, null, this.format, this._extension);
  29854. return;
  29855. }
  29856. };
  29857. InternalTexture.prototype._swapAndDie = function (target) {
  29858. target._webGLTexture = this._webGLTexture;
  29859. if (this._framebuffer) {
  29860. target._framebuffer = this._framebuffer;
  29861. }
  29862. if (this._depthStencilBuffer) {
  29863. target._depthStencilBuffer = this._depthStencilBuffer;
  29864. }
  29865. if (this._lodTextureHigh) {
  29866. if (target._lodTextureHigh) {
  29867. target._lodTextureHigh.dispose();
  29868. }
  29869. target._lodTextureHigh = this._lodTextureHigh;
  29870. }
  29871. if (this._lodTextureMid) {
  29872. if (target._lodTextureMid) {
  29873. target._lodTextureMid.dispose();
  29874. }
  29875. target._lodTextureMid = this._lodTextureMid;
  29876. }
  29877. if (this._lodTextureLow) {
  29878. if (target._lodTextureLow) {
  29879. target._lodTextureLow.dispose();
  29880. }
  29881. target._lodTextureLow = this._lodTextureLow;
  29882. }
  29883. var cache = this._engine.getLoadedTexturesCache();
  29884. var index = cache.indexOf(this);
  29885. if (index !== -1) {
  29886. cache.splice(index, 1);
  29887. }
  29888. };
  29889. /**
  29890. * Dispose the current allocated resources
  29891. */
  29892. InternalTexture.prototype.dispose = function () {
  29893. if (!this._webGLTexture) {
  29894. return;
  29895. }
  29896. this._references--;
  29897. if (this._references === 0) {
  29898. this._engine._releaseTexture(this);
  29899. this._webGLTexture = null;
  29900. this.previous = null;
  29901. this.next = null;
  29902. }
  29903. };
  29904. /**
  29905. * The source of the texture data is unknown
  29906. */
  29907. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29908. /**
  29909. * Texture data comes from an URL
  29910. */
  29911. InternalTexture.DATASOURCE_URL = 1;
  29912. /**
  29913. * Texture data is only used for temporary storage
  29914. */
  29915. InternalTexture.DATASOURCE_TEMP = 2;
  29916. /**
  29917. * Texture data comes from raw data (ArrayBuffer)
  29918. */
  29919. InternalTexture.DATASOURCE_RAW = 3;
  29920. /**
  29921. * Texture content is dynamic (video or dynamic texture)
  29922. */
  29923. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29924. /**
  29925. * Texture content is generated by rendering to it
  29926. */
  29927. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29928. /**
  29929. * Texture content is part of a multi render target process
  29930. */
  29931. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29932. /**
  29933. * Texture data comes from a cube data file
  29934. */
  29935. InternalTexture.DATASOURCE_CUBE = 7;
  29936. /**
  29937. * Texture data comes from a raw cube data
  29938. */
  29939. InternalTexture.DATASOURCE_CUBERAW = 8;
  29940. /**
  29941. * Texture data come from a prefiltered cube data file
  29942. */
  29943. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29944. /**
  29945. * Texture content is raw 3D data
  29946. */
  29947. InternalTexture.DATASOURCE_RAW3D = 10;
  29948. /**
  29949. * Texture content is a depth texture
  29950. */
  29951. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29952. return InternalTexture;
  29953. }());
  29954. BABYLON.InternalTexture = InternalTexture;
  29955. })(BABYLON || (BABYLON = {}));
  29956. //# sourceMappingURL=babylon.internalTexture.js.map
  29957. var BABYLON;
  29958. (function (BABYLON) {
  29959. var BaseTexture = /** @class */ (function () {
  29960. function BaseTexture(scene) {
  29961. this._hasAlpha = false;
  29962. this.getAlphaFromRGB = false;
  29963. this.level = 1;
  29964. this.coordinatesIndex = 0;
  29965. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29966. /**
  29967. * | Value | Type | Description |
  29968. * | ----- | ------------------ | ----------- |
  29969. * | 0 | CLAMP_ADDRESSMODE | |
  29970. * | 1 | WRAP_ADDRESSMODE | |
  29971. * | 2 | MIRROR_ADDRESSMODE | |
  29972. */
  29973. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29974. /**
  29975. * | Value | Type | Description |
  29976. * | ----- | ------------------ | ----------- |
  29977. * | 0 | CLAMP_ADDRESSMODE | |
  29978. * | 1 | WRAP_ADDRESSMODE | |
  29979. * | 2 | MIRROR_ADDRESSMODE | |
  29980. */
  29981. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29982. /**
  29983. * | Value | Type | Description |
  29984. * | ----- | ------------------ | ----------- |
  29985. * | 0 | CLAMP_ADDRESSMODE | |
  29986. * | 1 | WRAP_ADDRESSMODE | |
  29987. * | 2 | MIRROR_ADDRESSMODE | |
  29988. */
  29989. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29990. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29991. this.isCube = false;
  29992. this.is3D = false;
  29993. this.gammaSpace = true;
  29994. this.invertZ = false;
  29995. this.lodLevelInAlpha = false;
  29996. this.lodGenerationOffset = 0.0;
  29997. this.lodGenerationScale = 0.8;
  29998. this.isRenderTarget = false;
  29999. this.animations = new Array();
  30000. /**
  30001. * An event triggered when the texture is disposed.
  30002. */
  30003. this.onDisposeObservable = new BABYLON.Observable();
  30004. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30005. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30006. if (this._scene) {
  30007. this._scene.textures.push(this);
  30008. }
  30009. this._uid = null;
  30010. }
  30011. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30012. get: function () {
  30013. return this._hasAlpha;
  30014. },
  30015. set: function (value) {
  30016. if (this._hasAlpha === value) {
  30017. return;
  30018. }
  30019. this._hasAlpha = value;
  30020. if (this._scene) {
  30021. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30022. }
  30023. },
  30024. enumerable: true,
  30025. configurable: true
  30026. });
  30027. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30028. get: function () {
  30029. return this._coordinatesMode;
  30030. },
  30031. /**
  30032. * How a texture is mapped.
  30033. *
  30034. * | Value | Type | Description |
  30035. * | ----- | ----------------------------------- | ----------- |
  30036. * | 0 | EXPLICIT_MODE | |
  30037. * | 1 | SPHERICAL_MODE | |
  30038. * | 2 | PLANAR_MODE | |
  30039. * | 3 | CUBIC_MODE | |
  30040. * | 4 | PROJECTION_MODE | |
  30041. * | 5 | SKYBOX_MODE | |
  30042. * | 6 | INVCUBIC_MODE | |
  30043. * | 7 | EQUIRECTANGULAR_MODE | |
  30044. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30045. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30046. */
  30047. set: function (value) {
  30048. if (this._coordinatesMode === value) {
  30049. return;
  30050. }
  30051. this._coordinatesMode = value;
  30052. if (this._scene) {
  30053. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30054. }
  30055. },
  30056. enumerable: true,
  30057. configurable: true
  30058. });
  30059. Object.defineProperty(BaseTexture.prototype, "uid", {
  30060. get: function () {
  30061. if (!this._uid) {
  30062. this._uid = BABYLON.Tools.RandomId();
  30063. }
  30064. return this._uid;
  30065. },
  30066. enumerable: true,
  30067. configurable: true
  30068. });
  30069. BaseTexture.prototype.toString = function () {
  30070. return this.name;
  30071. };
  30072. BaseTexture.prototype.getClassName = function () {
  30073. return "BaseTexture";
  30074. };
  30075. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30076. set: function (callback) {
  30077. if (this._onDisposeObserver) {
  30078. this.onDisposeObservable.remove(this._onDisposeObserver);
  30079. }
  30080. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30081. },
  30082. enumerable: true,
  30083. configurable: true
  30084. });
  30085. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30086. get: function () {
  30087. return true;
  30088. },
  30089. enumerable: true,
  30090. configurable: true
  30091. });
  30092. BaseTexture.prototype.getScene = function () {
  30093. return this._scene;
  30094. };
  30095. BaseTexture.prototype.getTextureMatrix = function () {
  30096. return BABYLON.Matrix.IdentityReadOnly;
  30097. };
  30098. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30099. return BABYLON.Matrix.IdentityReadOnly;
  30100. };
  30101. BaseTexture.prototype.getInternalTexture = function () {
  30102. return this._texture;
  30103. };
  30104. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30105. return !this.isBlocking || this.isReady();
  30106. };
  30107. BaseTexture.prototype.isReady = function () {
  30108. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30109. this.delayLoad();
  30110. return false;
  30111. }
  30112. if (this._texture) {
  30113. return this._texture.isReady;
  30114. }
  30115. return false;
  30116. };
  30117. BaseTexture.prototype.getSize = function () {
  30118. if (this._texture && this._texture.width) {
  30119. return new BABYLON.Size(this._texture.width, this._texture.height);
  30120. }
  30121. if (this._texture && this._texture._size) {
  30122. return new BABYLON.Size(this._texture._size, this._texture._size);
  30123. }
  30124. return BABYLON.Size.Zero();
  30125. };
  30126. BaseTexture.prototype.getBaseSize = function () {
  30127. if (!this.isReady() || !this._texture)
  30128. return BABYLON.Size.Zero();
  30129. if (this._texture._size) {
  30130. return new BABYLON.Size(this._texture._size, this._texture._size);
  30131. }
  30132. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30133. };
  30134. BaseTexture.prototype.scale = function (ratio) {
  30135. };
  30136. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30137. get: function () {
  30138. return false;
  30139. },
  30140. enumerable: true,
  30141. configurable: true
  30142. });
  30143. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30144. if (!this._scene) {
  30145. return null;
  30146. }
  30147. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30148. for (var index = 0; index < texturesCache.length; index++) {
  30149. var texturesCacheEntry = texturesCache[index];
  30150. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30151. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30152. texturesCacheEntry.incrementReferences();
  30153. return texturesCacheEntry;
  30154. }
  30155. }
  30156. }
  30157. return null;
  30158. };
  30159. BaseTexture.prototype._rebuild = function () {
  30160. };
  30161. BaseTexture.prototype.delayLoad = function () {
  30162. };
  30163. BaseTexture.prototype.clone = function () {
  30164. return null;
  30165. };
  30166. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30167. get: function () {
  30168. if (!this._texture) {
  30169. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30170. }
  30171. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30172. },
  30173. enumerable: true,
  30174. configurable: true
  30175. });
  30176. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30177. get: function () {
  30178. if (!this._texture) {
  30179. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30180. }
  30181. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30182. },
  30183. enumerable: true,
  30184. configurable: true
  30185. });
  30186. BaseTexture.prototype.readPixels = function (faceIndex) {
  30187. if (faceIndex === void 0) { faceIndex = 0; }
  30188. if (!this._texture) {
  30189. return null;
  30190. }
  30191. var size = this.getSize();
  30192. var scene = this.getScene();
  30193. if (!scene) {
  30194. return null;
  30195. }
  30196. var engine = scene.getEngine();
  30197. if (this._texture.isCube) {
  30198. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30199. }
  30200. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30201. };
  30202. BaseTexture.prototype.releaseInternalTexture = function () {
  30203. if (this._texture) {
  30204. this._texture.dispose();
  30205. this._texture = null;
  30206. }
  30207. };
  30208. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30209. get: function () {
  30210. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30211. return null;
  30212. }
  30213. if (!this._texture._sphericalPolynomial) {
  30214. this._texture._sphericalPolynomial =
  30215. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30216. }
  30217. return this._texture._sphericalPolynomial;
  30218. },
  30219. set: function (value) {
  30220. if (this._texture) {
  30221. this._texture._sphericalPolynomial = value;
  30222. }
  30223. },
  30224. enumerable: true,
  30225. configurable: true
  30226. });
  30227. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30228. get: function () {
  30229. if (this._texture) {
  30230. return this._texture._lodTextureHigh;
  30231. }
  30232. return null;
  30233. },
  30234. enumerable: true,
  30235. configurable: true
  30236. });
  30237. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30238. get: function () {
  30239. if (this._texture) {
  30240. return this._texture._lodTextureMid;
  30241. }
  30242. return null;
  30243. },
  30244. enumerable: true,
  30245. configurable: true
  30246. });
  30247. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30248. get: function () {
  30249. if (this._texture) {
  30250. return this._texture._lodTextureLow;
  30251. }
  30252. return null;
  30253. },
  30254. enumerable: true,
  30255. configurable: true
  30256. });
  30257. BaseTexture.prototype.dispose = function () {
  30258. if (!this._scene) {
  30259. return;
  30260. }
  30261. // Animations
  30262. this._scene.stopAnimation(this);
  30263. // Remove from scene
  30264. this._scene._removePendingData(this);
  30265. var index = this._scene.textures.indexOf(this);
  30266. if (index >= 0) {
  30267. this._scene.textures.splice(index, 1);
  30268. }
  30269. if (this._texture === undefined) {
  30270. return;
  30271. }
  30272. // Release
  30273. this.releaseInternalTexture();
  30274. // Callback
  30275. this.onDisposeObservable.notifyObservers(this);
  30276. this.onDisposeObservable.clear();
  30277. };
  30278. BaseTexture.prototype.serialize = function () {
  30279. if (!this.name) {
  30280. return null;
  30281. }
  30282. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30283. // Animations
  30284. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30285. return serializationObject;
  30286. };
  30287. BaseTexture.WhenAllReady = function (textures, callback) {
  30288. var numRemaining = textures.length;
  30289. if (numRemaining === 0) {
  30290. callback();
  30291. return;
  30292. }
  30293. var _loop_1 = function () {
  30294. texture = textures[i];
  30295. if (texture.isReady()) {
  30296. if (--numRemaining === 0) {
  30297. callback();
  30298. }
  30299. }
  30300. else {
  30301. onLoadObservable = texture.onLoadObservable;
  30302. var onLoadCallback_1 = function () {
  30303. onLoadObservable.removeCallback(onLoadCallback_1);
  30304. if (--numRemaining === 0) {
  30305. callback();
  30306. }
  30307. };
  30308. onLoadObservable.add(onLoadCallback_1);
  30309. }
  30310. };
  30311. var texture, onLoadObservable;
  30312. for (var i = 0; i < textures.length; i++) {
  30313. _loop_1();
  30314. }
  30315. };
  30316. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30317. __decorate([
  30318. BABYLON.serialize()
  30319. ], BaseTexture.prototype, "name", void 0);
  30320. __decorate([
  30321. BABYLON.serialize("hasAlpha")
  30322. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30323. __decorate([
  30324. BABYLON.serialize()
  30325. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30326. __decorate([
  30327. BABYLON.serialize()
  30328. ], BaseTexture.prototype, "level", void 0);
  30329. __decorate([
  30330. BABYLON.serialize()
  30331. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30332. __decorate([
  30333. BABYLON.serialize("coordinatesMode")
  30334. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30335. __decorate([
  30336. BABYLON.serialize()
  30337. ], BaseTexture.prototype, "wrapU", void 0);
  30338. __decorate([
  30339. BABYLON.serialize()
  30340. ], BaseTexture.prototype, "wrapV", void 0);
  30341. __decorate([
  30342. BABYLON.serialize()
  30343. ], BaseTexture.prototype, "wrapR", void 0);
  30344. __decorate([
  30345. BABYLON.serialize()
  30346. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30347. __decorate([
  30348. BABYLON.serialize()
  30349. ], BaseTexture.prototype, "isCube", void 0);
  30350. __decorate([
  30351. BABYLON.serialize()
  30352. ], BaseTexture.prototype, "is3D", void 0);
  30353. __decorate([
  30354. BABYLON.serialize()
  30355. ], BaseTexture.prototype, "gammaSpace", void 0);
  30356. __decorate([
  30357. BABYLON.serialize()
  30358. ], BaseTexture.prototype, "invertZ", void 0);
  30359. __decorate([
  30360. BABYLON.serialize()
  30361. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30362. __decorate([
  30363. BABYLON.serialize()
  30364. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30365. __decorate([
  30366. BABYLON.serialize()
  30367. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30368. __decorate([
  30369. BABYLON.serialize()
  30370. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30371. return BaseTexture;
  30372. }());
  30373. BABYLON.BaseTexture = BaseTexture;
  30374. })(BABYLON || (BABYLON = {}));
  30375. //# sourceMappingURL=babylon.baseTexture.js.map
  30376. var BABYLON;
  30377. (function (BABYLON) {
  30378. var Texture = /** @class */ (function (_super) {
  30379. __extends(Texture, _super);
  30380. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30381. if (noMipmap === void 0) { noMipmap = false; }
  30382. if (invertY === void 0) { invertY = true; }
  30383. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30384. if (onLoad === void 0) { onLoad = null; }
  30385. if (onError === void 0) { onError = null; }
  30386. if (buffer === void 0) { buffer = null; }
  30387. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30388. var _this = _super.call(this, scene) || this;
  30389. _this.uOffset = 0;
  30390. _this.vOffset = 0;
  30391. _this.uScale = 1.0;
  30392. _this.vScale = 1.0;
  30393. _this.uAng = 0;
  30394. _this.vAng = 0;
  30395. _this.wAng = 0;
  30396. _this._isBlocking = true;
  30397. _this.name = url || "";
  30398. _this.url = url;
  30399. _this._noMipmap = noMipmap;
  30400. _this._invertY = invertY;
  30401. _this._samplingMode = samplingMode;
  30402. _this._buffer = buffer;
  30403. _this._deleteBuffer = deleteBuffer;
  30404. if (format) {
  30405. _this._format = format;
  30406. }
  30407. scene = _this.getScene();
  30408. if (!scene) {
  30409. return _this;
  30410. }
  30411. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30412. var load = function () {
  30413. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30414. _this.onLoadObservable.notifyObservers(_this);
  30415. }
  30416. if (onLoad) {
  30417. onLoad();
  30418. }
  30419. if (!_this.isBlocking && scene) {
  30420. scene.resetCachedMaterial();
  30421. }
  30422. };
  30423. if (!_this.url) {
  30424. _this._delayedOnLoad = load;
  30425. _this._delayedOnError = onError;
  30426. return _this;
  30427. }
  30428. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30429. if (!_this._texture) {
  30430. if (!scene.useDelayedTextureLoading) {
  30431. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30432. if (deleteBuffer) {
  30433. delete _this._buffer;
  30434. }
  30435. }
  30436. else {
  30437. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30438. _this._delayedOnLoad = load;
  30439. _this._delayedOnError = onError;
  30440. }
  30441. }
  30442. else {
  30443. if (_this._texture.isReady) {
  30444. BABYLON.Tools.SetImmediate(function () { return load(); });
  30445. }
  30446. else {
  30447. _this._texture.onLoadedObservable.add(load);
  30448. }
  30449. }
  30450. return _this;
  30451. }
  30452. Object.defineProperty(Texture.prototype, "noMipmap", {
  30453. get: function () {
  30454. return this._noMipmap;
  30455. },
  30456. enumerable: true,
  30457. configurable: true
  30458. });
  30459. Object.defineProperty(Texture.prototype, "isBlocking", {
  30460. get: function () {
  30461. return this._isBlocking;
  30462. },
  30463. set: function (value) {
  30464. this._isBlocking = value;
  30465. },
  30466. enumerable: true,
  30467. configurable: true
  30468. });
  30469. Object.defineProperty(Texture.prototype, "samplingMode", {
  30470. get: function () {
  30471. return this._samplingMode;
  30472. },
  30473. enumerable: true,
  30474. configurable: true
  30475. });
  30476. Texture.prototype.updateURL = function (url) {
  30477. this.url = url;
  30478. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30479. this.delayLoad();
  30480. };
  30481. Texture.prototype.delayLoad = function () {
  30482. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30483. return;
  30484. }
  30485. var scene = this.getScene();
  30486. if (!scene) {
  30487. return;
  30488. }
  30489. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30490. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30491. if (!this._texture) {
  30492. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30493. if (this._deleteBuffer) {
  30494. delete this._buffer;
  30495. }
  30496. }
  30497. else {
  30498. if (this._delayedOnLoad) {
  30499. if (this._texture.isReady) {
  30500. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30501. }
  30502. else {
  30503. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30504. }
  30505. }
  30506. }
  30507. this._delayedOnLoad = null;
  30508. this._delayedOnError = null;
  30509. };
  30510. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30511. if (!this._texture) {
  30512. return;
  30513. }
  30514. var scene = this.getScene();
  30515. if (!scene) {
  30516. return;
  30517. }
  30518. this._samplingMode = samplingMode;
  30519. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30520. };
  30521. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30522. x *= this.uScale;
  30523. y *= this.vScale;
  30524. x -= 0.5 * this.uScale;
  30525. y -= 0.5 * this.vScale;
  30526. z -= 0.5;
  30527. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30528. t.x += 0.5 * this.uScale + this.uOffset;
  30529. t.y += 0.5 * this.vScale + this.vOffset;
  30530. t.z += 0.5;
  30531. };
  30532. Texture.prototype.getTextureMatrix = function () {
  30533. var _this = this;
  30534. if (this.uOffset === this._cachedUOffset &&
  30535. this.vOffset === this._cachedVOffset &&
  30536. this.uScale === this._cachedUScale &&
  30537. this.vScale === this._cachedVScale &&
  30538. this.uAng === this._cachedUAng &&
  30539. this.vAng === this._cachedVAng &&
  30540. this.wAng === this._cachedWAng) {
  30541. return this._cachedTextureMatrix;
  30542. }
  30543. this._cachedUOffset = this.uOffset;
  30544. this._cachedVOffset = this.vOffset;
  30545. this._cachedUScale = this.uScale;
  30546. this._cachedVScale = this.vScale;
  30547. this._cachedUAng = this.uAng;
  30548. this._cachedVAng = this.vAng;
  30549. this._cachedWAng = this.wAng;
  30550. if (!this._cachedTextureMatrix) {
  30551. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30552. this._rowGenerationMatrix = new BABYLON.Matrix();
  30553. this._t0 = BABYLON.Vector3.Zero();
  30554. this._t1 = BABYLON.Vector3.Zero();
  30555. this._t2 = BABYLON.Vector3.Zero();
  30556. }
  30557. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30558. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30559. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30560. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30561. this._t1.subtractInPlace(this._t0);
  30562. this._t2.subtractInPlace(this._t0);
  30563. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30564. this._cachedTextureMatrix.m[0] = this._t1.x;
  30565. this._cachedTextureMatrix.m[1] = this._t1.y;
  30566. this._cachedTextureMatrix.m[2] = this._t1.z;
  30567. this._cachedTextureMatrix.m[4] = this._t2.x;
  30568. this._cachedTextureMatrix.m[5] = this._t2.y;
  30569. this._cachedTextureMatrix.m[6] = this._t2.z;
  30570. this._cachedTextureMatrix.m[8] = this._t0.x;
  30571. this._cachedTextureMatrix.m[9] = this._t0.y;
  30572. this._cachedTextureMatrix.m[10] = this._t0.z;
  30573. var scene = this.getScene();
  30574. if (!scene) {
  30575. return this._cachedTextureMatrix;
  30576. }
  30577. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30578. return mat.hasTexture(_this);
  30579. });
  30580. return this._cachedTextureMatrix;
  30581. };
  30582. Texture.prototype.getReflectionTextureMatrix = function () {
  30583. var _this = this;
  30584. var scene = this.getScene();
  30585. if (!scene) {
  30586. return this._cachedTextureMatrix;
  30587. }
  30588. if (this.uOffset === this._cachedUOffset &&
  30589. this.vOffset === this._cachedVOffset &&
  30590. this.uScale === this._cachedUScale &&
  30591. this.vScale === this._cachedVScale &&
  30592. this.coordinatesMode === this._cachedCoordinatesMode) {
  30593. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30594. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30595. return this._cachedTextureMatrix;
  30596. }
  30597. }
  30598. else {
  30599. return this._cachedTextureMatrix;
  30600. }
  30601. }
  30602. if (!this._cachedTextureMatrix) {
  30603. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30604. }
  30605. if (!this._projectionModeMatrix) {
  30606. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30607. }
  30608. this._cachedUOffset = this.uOffset;
  30609. this._cachedVOffset = this.vOffset;
  30610. this._cachedUScale = this.uScale;
  30611. this._cachedVScale = this.vScale;
  30612. this._cachedCoordinatesMode = this.coordinatesMode;
  30613. switch (this.coordinatesMode) {
  30614. case Texture.PLANAR_MODE:
  30615. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30616. this._cachedTextureMatrix[0] = this.uScale;
  30617. this._cachedTextureMatrix[5] = this.vScale;
  30618. this._cachedTextureMatrix[12] = this.uOffset;
  30619. this._cachedTextureMatrix[13] = this.vOffset;
  30620. break;
  30621. case Texture.PROJECTION_MODE:
  30622. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30623. this._projectionModeMatrix.m[0] = 0.5;
  30624. this._projectionModeMatrix.m[5] = -0.5;
  30625. this._projectionModeMatrix.m[10] = 0.0;
  30626. this._projectionModeMatrix.m[12] = 0.5;
  30627. this._projectionModeMatrix.m[13] = 0.5;
  30628. this._projectionModeMatrix.m[14] = 1.0;
  30629. this._projectionModeMatrix.m[15] = 1.0;
  30630. var projectionMatrix = scene.getProjectionMatrix();
  30631. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30632. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30633. break;
  30634. default:
  30635. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30636. break;
  30637. }
  30638. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30639. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30640. });
  30641. return this._cachedTextureMatrix;
  30642. };
  30643. Texture.prototype.clone = function () {
  30644. var _this = this;
  30645. return BABYLON.SerializationHelper.Clone(function () {
  30646. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30647. }, this);
  30648. };
  30649. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30650. get: function () {
  30651. if (!this._onLoadObservable) {
  30652. this._onLoadObservable = new BABYLON.Observable();
  30653. }
  30654. return this._onLoadObservable;
  30655. },
  30656. enumerable: true,
  30657. configurable: true
  30658. });
  30659. Texture.prototype.serialize = function () {
  30660. var serializationObject = _super.prototype.serialize.call(this);
  30661. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30662. serializationObject.base64String = this._buffer;
  30663. serializationObject.name = serializationObject.name.replace("data:", "");
  30664. }
  30665. serializationObject.invertY = this._invertY;
  30666. serializationObject.samplingMode = this.samplingMode;
  30667. return serializationObject;
  30668. };
  30669. Texture.prototype.getClassName = function () {
  30670. return "Texture";
  30671. };
  30672. Texture.prototype.dispose = function () {
  30673. _super.prototype.dispose.call(this);
  30674. if (this.onLoadObservable) {
  30675. this.onLoadObservable.clear();
  30676. this._onLoadObservable = null;
  30677. }
  30678. this._delayedOnLoad = null;
  30679. this._delayedOnError = null;
  30680. };
  30681. // Statics
  30682. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30683. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30684. if (onLoad === void 0) { onLoad = null; }
  30685. if (onError === void 0) { onError = null; }
  30686. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30687. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30688. };
  30689. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30690. if (parsedTexture.customType) {
  30691. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30692. // Update Sampling Mode
  30693. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30694. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30695. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30696. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30697. }
  30698. }
  30699. return parsedCustomTexture;
  30700. }
  30701. if (parsedTexture.isCube) {
  30702. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30703. }
  30704. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30705. return null;
  30706. }
  30707. var texture = BABYLON.SerializationHelper.Parse(function () {
  30708. var generateMipMaps = true;
  30709. if (parsedTexture.noMipmap) {
  30710. generateMipMaps = false;
  30711. }
  30712. if (parsedTexture.mirrorPlane) {
  30713. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30714. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30715. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30716. return mirrorTexture;
  30717. }
  30718. else if (parsedTexture.isRenderTarget) {
  30719. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30720. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30721. return renderTargetTexture;
  30722. }
  30723. else {
  30724. var texture;
  30725. if (parsedTexture.base64String) {
  30726. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30727. }
  30728. else {
  30729. var url = rootUrl + parsedTexture.name;
  30730. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30731. url = parsedTexture.url;
  30732. }
  30733. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30734. }
  30735. return texture;
  30736. }
  30737. }, parsedTexture, scene);
  30738. // Update Sampling Mode
  30739. if (parsedTexture.samplingMode) {
  30740. var sampling = parsedTexture.samplingMode;
  30741. if (texture._samplingMode !== sampling) {
  30742. texture.updateSamplingMode(sampling);
  30743. }
  30744. }
  30745. // Animations
  30746. if (parsedTexture.animations) {
  30747. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30748. var parsedAnimation = parsedTexture.animations[animationIndex];
  30749. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30750. }
  30751. }
  30752. return texture;
  30753. };
  30754. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30755. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30756. if (noMipmap === void 0) { noMipmap = false; }
  30757. if (invertY === void 0) { invertY = true; }
  30758. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30759. if (onLoad === void 0) { onLoad = null; }
  30760. if (onError === void 0) { onError = null; }
  30761. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30762. if (name.substr(0, 5) !== "data:") {
  30763. name = "data:" + name;
  30764. }
  30765. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30766. };
  30767. // Constants
  30768. Texture.NEAREST_SAMPLINGMODE = 1;
  30769. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30770. Texture.BILINEAR_SAMPLINGMODE = 2;
  30771. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30772. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30773. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30774. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30775. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30776. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30777. Texture.NEAREST_LINEAR = 7;
  30778. Texture.NEAREST_NEAREST = 8;
  30779. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30780. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30781. Texture.LINEAR_LINEAR = 11;
  30782. Texture.LINEAR_NEAREST = 12;
  30783. Texture.EXPLICIT_MODE = 0;
  30784. Texture.SPHERICAL_MODE = 1;
  30785. Texture.PLANAR_MODE = 2;
  30786. Texture.CUBIC_MODE = 3;
  30787. Texture.PROJECTION_MODE = 4;
  30788. Texture.SKYBOX_MODE = 5;
  30789. Texture.INVCUBIC_MODE = 6;
  30790. Texture.EQUIRECTANGULAR_MODE = 7;
  30791. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30792. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30793. Texture.CLAMP_ADDRESSMODE = 0;
  30794. Texture.WRAP_ADDRESSMODE = 1;
  30795. Texture.MIRROR_ADDRESSMODE = 2;
  30796. /**
  30797. * 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
  30798. */
  30799. Texture.UseSerializedUrlIfAny = false;
  30800. __decorate([
  30801. BABYLON.serialize()
  30802. ], Texture.prototype, "url", void 0);
  30803. __decorate([
  30804. BABYLON.serialize()
  30805. ], Texture.prototype, "uOffset", void 0);
  30806. __decorate([
  30807. BABYLON.serialize()
  30808. ], Texture.prototype, "vOffset", void 0);
  30809. __decorate([
  30810. BABYLON.serialize()
  30811. ], Texture.prototype, "uScale", void 0);
  30812. __decorate([
  30813. BABYLON.serialize()
  30814. ], Texture.prototype, "vScale", void 0);
  30815. __decorate([
  30816. BABYLON.serialize()
  30817. ], Texture.prototype, "uAng", void 0);
  30818. __decorate([
  30819. BABYLON.serialize()
  30820. ], Texture.prototype, "vAng", void 0);
  30821. __decorate([
  30822. BABYLON.serialize()
  30823. ], Texture.prototype, "wAng", void 0);
  30824. __decorate([
  30825. BABYLON.serialize()
  30826. ], Texture.prototype, "isBlocking", null);
  30827. return Texture;
  30828. }(BABYLON.BaseTexture));
  30829. BABYLON.Texture = Texture;
  30830. })(BABYLON || (BABYLON = {}));
  30831. //# sourceMappingURL=babylon.texture.js.map
  30832. var BABYLON;
  30833. (function (BABYLON) {
  30834. /**
  30835. * @hidden
  30836. **/
  30837. var _InstancesBatch = /** @class */ (function () {
  30838. function _InstancesBatch() {
  30839. this.mustReturn = false;
  30840. this.visibleInstances = new Array();
  30841. this.renderSelf = new Array();
  30842. }
  30843. return _InstancesBatch;
  30844. }());
  30845. BABYLON._InstancesBatch = _InstancesBatch;
  30846. var Mesh = /** @class */ (function (_super) {
  30847. __extends(Mesh, _super);
  30848. /**
  30849. * @constructor
  30850. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30851. * @param {Scene} scene The scene to add this mesh to.
  30852. * @param {Node} parent The parent of this mesh, if it has one
  30853. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30854. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30855. * When false, achieved by calling a clone(), also passing False.
  30856. * This will make creation of children, recursive.
  30857. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30858. */
  30859. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30860. if (scene === void 0) { scene = null; }
  30861. if (parent === void 0) { parent = null; }
  30862. if (source === void 0) { source = null; }
  30863. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30864. var _this = _super.call(this, name, scene) || this;
  30865. // Events
  30866. /**
  30867. * An event triggered before rendering the mesh
  30868. */
  30869. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30870. /**
  30871. * An event triggered after rendering the mesh
  30872. */
  30873. _this.onAfterRenderObservable = new BABYLON.Observable();
  30874. /**
  30875. * An event triggered before drawing the mesh
  30876. */
  30877. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30878. // Members
  30879. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30880. _this.instances = new Array();
  30881. _this._LODLevels = new Array();
  30882. _this._visibleInstances = {};
  30883. _this._renderIdForInstances = new Array();
  30884. _this._batchCache = new _InstancesBatch();
  30885. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30886. // Use by builder only to know what orientation were the mesh build in.
  30887. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30888. _this.overrideMaterialSideOrientation = null;
  30889. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30890. // Will be used to save a source mesh reference, If any
  30891. _this._source = null;
  30892. scene = _this.getScene();
  30893. if (source) {
  30894. // Source mesh
  30895. _this._source = source;
  30896. // Geometry
  30897. if (source._geometry) {
  30898. source._geometry.applyToMesh(_this);
  30899. }
  30900. // Deep copy
  30901. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30902. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30903. // Metadata
  30904. if (source.metadata && source.metadata.clone) {
  30905. _this.metadata = source.metadata.clone();
  30906. }
  30907. else {
  30908. _this.metadata = source.metadata;
  30909. }
  30910. // Tags
  30911. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30912. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30913. }
  30914. // Parent
  30915. _this.parent = source.parent;
  30916. // Pivot
  30917. _this.setPivotMatrix(source.getPivotMatrix());
  30918. _this.id = name + "." + source.id;
  30919. // Material
  30920. _this.material = source.material;
  30921. var index;
  30922. if (!doNotCloneChildren) {
  30923. // Children
  30924. var directDescendants = source.getDescendants(true);
  30925. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30926. var child = directDescendants[index_1];
  30927. if (child.clone) {
  30928. child.clone(name + "." + child.name, _this);
  30929. }
  30930. }
  30931. }
  30932. // Physics clone
  30933. var physicsEngine = _this.getScene().getPhysicsEngine();
  30934. if (clonePhysicsImpostor && physicsEngine) {
  30935. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30936. if (impostor) {
  30937. _this.physicsImpostor = impostor.clone(_this);
  30938. }
  30939. }
  30940. // Particles
  30941. for (index = 0; index < scene.particleSystems.length; index++) {
  30942. var system = scene.particleSystems[index];
  30943. if (system.emitter === source) {
  30944. system.clone(system.name, _this);
  30945. }
  30946. }
  30947. _this.computeWorldMatrix(true);
  30948. }
  30949. // Parent
  30950. if (parent !== null) {
  30951. _this.parent = parent;
  30952. }
  30953. return _this;
  30954. }
  30955. Object.defineProperty(Mesh, "FRONTSIDE", {
  30956. /**
  30957. * Mesh side orientation : usually the external or front surface
  30958. */
  30959. get: function () {
  30960. return Mesh._FRONTSIDE;
  30961. },
  30962. enumerable: true,
  30963. configurable: true
  30964. });
  30965. Object.defineProperty(Mesh, "BACKSIDE", {
  30966. /**
  30967. * Mesh side orientation : usually the internal or back surface
  30968. */
  30969. get: function () {
  30970. return Mesh._BACKSIDE;
  30971. },
  30972. enumerable: true,
  30973. configurable: true
  30974. });
  30975. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30976. /**
  30977. * Mesh side orientation : both internal and external or front and back surfaces
  30978. */
  30979. get: function () {
  30980. return Mesh._DOUBLESIDE;
  30981. },
  30982. enumerable: true,
  30983. configurable: true
  30984. });
  30985. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30986. /**
  30987. * Mesh side orientation : by default, `FRONTSIDE`
  30988. */
  30989. get: function () {
  30990. return Mesh._DEFAULTSIDE;
  30991. },
  30992. enumerable: true,
  30993. configurable: true
  30994. });
  30995. Object.defineProperty(Mesh, "NO_CAP", {
  30996. /**
  30997. * Mesh cap setting : no cap
  30998. */
  30999. get: function () {
  31000. return Mesh._NO_CAP;
  31001. },
  31002. enumerable: true,
  31003. configurable: true
  31004. });
  31005. Object.defineProperty(Mesh, "CAP_START", {
  31006. /**
  31007. * Mesh cap setting : one cap at the beginning of the mesh
  31008. */
  31009. get: function () {
  31010. return Mesh._CAP_START;
  31011. },
  31012. enumerable: true,
  31013. configurable: true
  31014. });
  31015. Object.defineProperty(Mesh, "CAP_END", {
  31016. /**
  31017. * Mesh cap setting : one cap at the end of the mesh
  31018. */
  31019. get: function () {
  31020. return Mesh._CAP_END;
  31021. },
  31022. enumerable: true,
  31023. configurable: true
  31024. });
  31025. Object.defineProperty(Mesh, "CAP_ALL", {
  31026. /**
  31027. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31028. */
  31029. get: function () {
  31030. return Mesh._CAP_ALL;
  31031. },
  31032. enumerable: true,
  31033. configurable: true
  31034. });
  31035. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31036. set: function (callback) {
  31037. if (this._onBeforeDrawObserver) {
  31038. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31039. }
  31040. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31041. },
  31042. enumerable: true,
  31043. configurable: true
  31044. });
  31045. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31046. get: function () {
  31047. return this._morphTargetManager;
  31048. },
  31049. set: function (value) {
  31050. if (this._morphTargetManager === value) {
  31051. return;
  31052. }
  31053. this._morphTargetManager = value;
  31054. this._syncGeometryWithMorphTargetManager();
  31055. },
  31056. enumerable: true,
  31057. configurable: true
  31058. });
  31059. Object.defineProperty(Mesh.prototype, "source", {
  31060. get: function () {
  31061. return this._source;
  31062. },
  31063. enumerable: true,
  31064. configurable: true
  31065. });
  31066. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31067. get: function () {
  31068. return this._unIndexed;
  31069. },
  31070. set: function (value) {
  31071. if (this._unIndexed !== value) {
  31072. this._unIndexed = value;
  31073. this._markSubMeshesAsAttributesDirty();
  31074. }
  31075. },
  31076. enumerable: true,
  31077. configurable: true
  31078. });
  31079. // Methods
  31080. /**
  31081. * Returns the string "Mesh".
  31082. */
  31083. Mesh.prototype.getClassName = function () {
  31084. return "Mesh";
  31085. };
  31086. /**
  31087. * Returns a string.
  31088. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31089. */
  31090. Mesh.prototype.toString = function (fullDetails) {
  31091. var ret = _super.prototype.toString.call(this, fullDetails);
  31092. ret += ", n vertices: " + this.getTotalVertices();
  31093. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31094. if (this.animations) {
  31095. for (var i = 0; i < this.animations.length; i++) {
  31096. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31097. }
  31098. }
  31099. if (fullDetails) {
  31100. if (this._geometry) {
  31101. var ib = this.getIndices();
  31102. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31103. if (vb && ib) {
  31104. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31105. }
  31106. }
  31107. else {
  31108. ret += ", flat shading: UNKNOWN";
  31109. }
  31110. }
  31111. return ret;
  31112. };
  31113. Mesh.prototype._unBindEffect = function () {
  31114. _super.prototype._unBindEffect.call(this);
  31115. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31116. var instance = _a[_i];
  31117. instance._unBindEffect();
  31118. }
  31119. };
  31120. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31121. /**
  31122. * True if the mesh has some Levels Of Details (LOD).
  31123. * Returns a boolean.
  31124. */
  31125. get: function () {
  31126. return this._LODLevels.length > 0;
  31127. },
  31128. enumerable: true,
  31129. configurable: true
  31130. });
  31131. /**
  31132. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31133. * @returns an array of {BABYLON.MeshLODLevel}
  31134. */
  31135. Mesh.prototype.getLODLevels = function () {
  31136. return this._LODLevels;
  31137. };
  31138. Mesh.prototype._sortLODLevels = function () {
  31139. this._LODLevels.sort(function (a, b) {
  31140. if (a.distance < b.distance) {
  31141. return 1;
  31142. }
  31143. if (a.distance > b.distance) {
  31144. return -1;
  31145. }
  31146. return 0;
  31147. });
  31148. };
  31149. /**
  31150. * Add a mesh as LOD level triggered at the given distance.
  31151. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31152. * @param {number} distance The distance from the center of the object to show this level
  31153. * @param {Mesh} mesh The mesh to be added as LOD level
  31154. * @return {Mesh} This mesh (for chaining)
  31155. */
  31156. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31157. if (mesh && mesh._masterMesh) {
  31158. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31159. return this;
  31160. }
  31161. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31162. this._LODLevels.push(level);
  31163. if (mesh) {
  31164. mesh._masterMesh = this;
  31165. }
  31166. this._sortLODLevels();
  31167. return this;
  31168. };
  31169. /**
  31170. * Returns the LOD level mesh at the passed distance or null if not found.
  31171. * It is related to the method `addLODLevel(distance, mesh)`.
  31172. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31173. * Returns an object Mesh or `null`.
  31174. */
  31175. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31176. for (var index = 0; index < this._LODLevels.length; index++) {
  31177. var level = this._LODLevels[index];
  31178. if (level.distance === distance) {
  31179. return level.mesh;
  31180. }
  31181. }
  31182. return null;
  31183. };
  31184. /**
  31185. * Remove a mesh from the LOD array
  31186. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31187. * @param {Mesh} mesh The mesh to be removed.
  31188. * @return {Mesh} This mesh (for chaining)
  31189. */
  31190. Mesh.prototype.removeLODLevel = function (mesh) {
  31191. for (var index = 0; index < this._LODLevels.length; index++) {
  31192. if (this._LODLevels[index].mesh === mesh) {
  31193. this._LODLevels.splice(index, 1);
  31194. if (mesh) {
  31195. mesh._masterMesh = null;
  31196. }
  31197. }
  31198. }
  31199. this._sortLODLevels();
  31200. return this;
  31201. };
  31202. /**
  31203. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31204. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31205. */
  31206. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31207. if (!this._LODLevels || this._LODLevels.length === 0) {
  31208. return this;
  31209. }
  31210. var bSphere;
  31211. if (boundingSphere) {
  31212. bSphere = boundingSphere;
  31213. }
  31214. else {
  31215. var boundingInfo = this.getBoundingInfo();
  31216. bSphere = boundingInfo.boundingSphere;
  31217. }
  31218. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31219. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31220. if (this.onLODLevelSelection) {
  31221. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31222. }
  31223. return this;
  31224. }
  31225. for (var index = 0; index < this._LODLevels.length; index++) {
  31226. var level = this._LODLevels[index];
  31227. if (level.distance < distanceToCamera) {
  31228. if (level.mesh) {
  31229. level.mesh._preActivate();
  31230. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31231. }
  31232. if (this.onLODLevelSelection) {
  31233. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31234. }
  31235. return level.mesh;
  31236. }
  31237. }
  31238. if (this.onLODLevelSelection) {
  31239. this.onLODLevelSelection(distanceToCamera, this, this);
  31240. }
  31241. return this;
  31242. };
  31243. Object.defineProperty(Mesh.prototype, "geometry", {
  31244. /**
  31245. * Returns the mesh internal Geometry object.
  31246. */
  31247. get: function () {
  31248. return this._geometry;
  31249. },
  31250. enumerable: true,
  31251. configurable: true
  31252. });
  31253. /**
  31254. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31255. */
  31256. Mesh.prototype.getTotalVertices = function () {
  31257. if (this._geometry === null || this._geometry === undefined) {
  31258. return 0;
  31259. }
  31260. return this._geometry.getTotalVertices();
  31261. };
  31262. /**
  31263. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31264. * 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.
  31265. * You can force the copy with forceCopy === true
  31266. * Returns null if the mesh has no geometry or no vertex buffer.
  31267. * Possible `kind` values :
  31268. * - BABYLON.VertexBuffer.PositionKind
  31269. * - BABYLON.VertexBuffer.UVKind
  31270. * - BABYLON.VertexBuffer.UV2Kind
  31271. * - BABYLON.VertexBuffer.UV3Kind
  31272. * - BABYLON.VertexBuffer.UV4Kind
  31273. * - BABYLON.VertexBuffer.UV5Kind
  31274. * - BABYLON.VertexBuffer.UV6Kind
  31275. * - BABYLON.VertexBuffer.ColorKind
  31276. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31277. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31278. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31279. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31280. */
  31281. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31282. if (!this._geometry) {
  31283. return null;
  31284. }
  31285. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31286. };
  31287. /**
  31288. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31289. * Returns `null` if the mesh has no geometry.
  31290. * Possible `kind` values :
  31291. * - BABYLON.VertexBuffer.PositionKind
  31292. * - BABYLON.VertexBuffer.UVKind
  31293. * - BABYLON.VertexBuffer.UV2Kind
  31294. * - BABYLON.VertexBuffer.UV3Kind
  31295. * - BABYLON.VertexBuffer.UV4Kind
  31296. * - BABYLON.VertexBuffer.UV5Kind
  31297. * - BABYLON.VertexBuffer.UV6Kind
  31298. * - BABYLON.VertexBuffer.ColorKind
  31299. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31300. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31301. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31302. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31303. */
  31304. Mesh.prototype.getVertexBuffer = function (kind) {
  31305. if (!this._geometry) {
  31306. return null;
  31307. }
  31308. return this._geometry.getVertexBuffer(kind);
  31309. };
  31310. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31311. if (!this._geometry) {
  31312. if (this._delayInfo) {
  31313. return this._delayInfo.indexOf(kind) !== -1;
  31314. }
  31315. return false;
  31316. }
  31317. return this._geometry.isVerticesDataPresent(kind);
  31318. };
  31319. /**
  31320. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31321. * Possible `kind` values :
  31322. * - BABYLON.VertexBuffer.PositionKind
  31323. * - BABYLON.VertexBuffer.UVKind
  31324. * - BABYLON.VertexBuffer.UV2Kind
  31325. * - BABYLON.VertexBuffer.UV3Kind
  31326. * - BABYLON.VertexBuffer.UV4Kind
  31327. * - BABYLON.VertexBuffer.UV5Kind
  31328. * - BABYLON.VertexBuffer.UV6Kind
  31329. * - BABYLON.VertexBuffer.ColorKind
  31330. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31331. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31332. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31333. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31334. */
  31335. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31336. if (!this._geometry) {
  31337. if (this._delayInfo) {
  31338. return this._delayInfo.indexOf(kind) !== -1;
  31339. }
  31340. return false;
  31341. }
  31342. return this._geometry.isVertexBufferUpdatable(kind);
  31343. };
  31344. /**
  31345. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31346. * Possible `kind` values :
  31347. * - BABYLON.VertexBuffer.PositionKind
  31348. * - BABYLON.VertexBuffer.UVKind
  31349. * - BABYLON.VertexBuffer.UV2Kind
  31350. * - BABYLON.VertexBuffer.UV3Kind
  31351. * - BABYLON.VertexBuffer.UV4Kind
  31352. * - BABYLON.VertexBuffer.UV5Kind
  31353. * - BABYLON.VertexBuffer.UV6Kind
  31354. * - BABYLON.VertexBuffer.ColorKind
  31355. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31356. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31357. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31358. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31359. */
  31360. Mesh.prototype.getVerticesDataKinds = function () {
  31361. if (!this._geometry) {
  31362. var result = new Array();
  31363. if (this._delayInfo) {
  31364. this._delayInfo.forEach(function (kind, index, array) {
  31365. result.push(kind);
  31366. });
  31367. }
  31368. return result;
  31369. }
  31370. return this._geometry.getVerticesDataKinds();
  31371. };
  31372. /**
  31373. * Returns a positive integer : the total number of indices in this mesh geometry.
  31374. * Returns zero if the mesh has no geometry.
  31375. */
  31376. Mesh.prototype.getTotalIndices = function () {
  31377. if (!this._geometry) {
  31378. return 0;
  31379. }
  31380. return this._geometry.getTotalIndices();
  31381. };
  31382. /**
  31383. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31384. * 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.
  31385. * Returns an empty array if the mesh has no geometry.
  31386. */
  31387. Mesh.prototype.getIndices = function (copyWhenShared) {
  31388. if (!this._geometry) {
  31389. return [];
  31390. }
  31391. return this._geometry.getIndices(copyWhenShared);
  31392. };
  31393. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31394. get: function () {
  31395. return this._masterMesh !== null && this._masterMesh !== undefined;
  31396. },
  31397. enumerable: true,
  31398. configurable: true
  31399. });
  31400. /**
  31401. * Determine if the current mesh is ready to be rendered
  31402. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31403. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31404. * @returns true if all associated assets are ready (material, textures, shaders)
  31405. */
  31406. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31407. if (completeCheck === void 0) { completeCheck = false; }
  31408. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31409. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31410. return false;
  31411. }
  31412. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31413. return false;
  31414. }
  31415. if (!this.subMeshes || this.subMeshes.length === 0) {
  31416. return true;
  31417. }
  31418. if (!completeCheck) {
  31419. return true;
  31420. }
  31421. var engine = this.getEngine();
  31422. var scene = this.getScene();
  31423. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31424. this.computeWorldMatrix();
  31425. var mat = this.material || scene.defaultMaterial;
  31426. if (mat) {
  31427. if (mat.storeEffectOnSubMeshes) {
  31428. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31429. var subMesh = _a[_i];
  31430. var effectiveMaterial = subMesh.getMaterial();
  31431. if (effectiveMaterial) {
  31432. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31433. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31434. return false;
  31435. }
  31436. }
  31437. else {
  31438. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31439. return false;
  31440. }
  31441. }
  31442. }
  31443. }
  31444. }
  31445. else {
  31446. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31447. return false;
  31448. }
  31449. }
  31450. }
  31451. // Shadows
  31452. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31453. var light = _c[_b];
  31454. var generator = light.getShadowGenerator();
  31455. if (generator) {
  31456. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31457. var subMesh = _e[_d];
  31458. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31459. return false;
  31460. }
  31461. }
  31462. }
  31463. }
  31464. // LOD
  31465. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31466. var lod = _g[_f];
  31467. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31468. return false;
  31469. }
  31470. }
  31471. return true;
  31472. };
  31473. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31474. /**
  31475. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31476. * This property is pertinent only for updatable parametric shapes.
  31477. */
  31478. get: function () {
  31479. return this._areNormalsFrozen;
  31480. },
  31481. enumerable: true,
  31482. configurable: true
  31483. });
  31484. /**
  31485. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31486. * It has no effect at all on other shapes.
  31487. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31488. * Returns the Mesh.
  31489. */
  31490. Mesh.prototype.freezeNormals = function () {
  31491. this._areNormalsFrozen = true;
  31492. return this;
  31493. };
  31494. /**
  31495. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31496. * It has no effect at all on other shapes.
  31497. * It reactivates the mesh normals computation if it was previously frozen.
  31498. * Returns the Mesh.
  31499. */
  31500. Mesh.prototype.unfreezeNormals = function () {
  31501. this._areNormalsFrozen = false;
  31502. return this;
  31503. };
  31504. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31505. /**
  31506. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31507. */
  31508. set: function (count) {
  31509. this._overridenInstanceCount = count;
  31510. },
  31511. enumerable: true,
  31512. configurable: true
  31513. });
  31514. // Methods
  31515. Mesh.prototype._preActivate = function () {
  31516. var sceneRenderId = this.getScene().getRenderId();
  31517. if (this._preActivateId === sceneRenderId) {
  31518. return this;
  31519. }
  31520. this._preActivateId = sceneRenderId;
  31521. this._visibleInstances = null;
  31522. return this;
  31523. };
  31524. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31525. if (this._visibleInstances) {
  31526. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31527. }
  31528. return this;
  31529. };
  31530. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31531. if (!this._visibleInstances) {
  31532. this._visibleInstances = {};
  31533. this._visibleInstances.defaultRenderId = renderId;
  31534. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31535. }
  31536. if (!this._visibleInstances[renderId]) {
  31537. this._visibleInstances[renderId] = new Array();
  31538. }
  31539. this._visibleInstances[renderId].push(instance);
  31540. return this;
  31541. };
  31542. /**
  31543. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31544. * This means the mesh underlying bounding box and sphere are recomputed.
  31545. * Returns the Mesh.
  31546. */
  31547. Mesh.prototype.refreshBoundingInfo = function () {
  31548. return this._refreshBoundingInfo(false);
  31549. };
  31550. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31551. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31552. return this;
  31553. }
  31554. var data = this._getPositionData(applySkeleton);
  31555. if (data) {
  31556. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31557. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31558. }
  31559. if (this.subMeshes) {
  31560. for (var index = 0; index < this.subMeshes.length; index++) {
  31561. this.subMeshes[index].refreshBoundingInfo();
  31562. }
  31563. }
  31564. this._updateBoundingInfo();
  31565. return this;
  31566. };
  31567. Mesh.prototype._getPositionData = function (applySkeleton) {
  31568. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31569. if (data && applySkeleton && this.skeleton) {
  31570. data = BABYLON.Tools.Slice(data);
  31571. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31572. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31573. if (matricesWeightsData && matricesIndicesData) {
  31574. var needExtras = this.numBoneInfluencers > 4;
  31575. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31576. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31577. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31578. var tempVector = BABYLON.Tmp.Vector3[0];
  31579. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31580. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31581. var matWeightIdx = 0;
  31582. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31583. finalMatrix.reset();
  31584. var inf;
  31585. var weight;
  31586. for (inf = 0; inf < 4; inf++) {
  31587. weight = matricesWeightsData[matWeightIdx + inf];
  31588. if (weight <= 0)
  31589. break;
  31590. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31591. finalMatrix.addToSelf(tempMatrix);
  31592. }
  31593. if (needExtras) {
  31594. for (inf = 0; inf < 4; inf++) {
  31595. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31596. if (weight <= 0)
  31597. break;
  31598. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31599. finalMatrix.addToSelf(tempMatrix);
  31600. }
  31601. }
  31602. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31603. tempVector.toArray(data, index);
  31604. }
  31605. }
  31606. }
  31607. return data;
  31608. };
  31609. Mesh.prototype._createGlobalSubMesh = function (force) {
  31610. var totalVertices = this.getTotalVertices();
  31611. if (!totalVertices || !this.getIndices()) {
  31612. return null;
  31613. }
  31614. // Check if we need to recreate the submeshes
  31615. if (this.subMeshes && this.subMeshes.length > 0) {
  31616. var ib = this.getIndices();
  31617. if (!ib) {
  31618. return null;
  31619. }
  31620. var totalIndices = ib.length;
  31621. var needToRecreate = false;
  31622. if (force) {
  31623. needToRecreate = true;
  31624. }
  31625. else {
  31626. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31627. var submesh = _a[_i];
  31628. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31629. needToRecreate = true;
  31630. break;
  31631. }
  31632. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31633. needToRecreate = true;
  31634. break;
  31635. }
  31636. }
  31637. }
  31638. if (!needToRecreate) {
  31639. return this.subMeshes[0];
  31640. }
  31641. }
  31642. this.releaseSubMeshes();
  31643. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31644. };
  31645. Mesh.prototype.subdivide = function (count) {
  31646. if (count < 1) {
  31647. return;
  31648. }
  31649. var totalIndices = this.getTotalIndices();
  31650. var subdivisionSize = (totalIndices / count) | 0;
  31651. var offset = 0;
  31652. // Ensure that subdivisionSize is a multiple of 3
  31653. while (subdivisionSize % 3 !== 0) {
  31654. subdivisionSize++;
  31655. }
  31656. this.releaseSubMeshes();
  31657. for (var index = 0; index < count; index++) {
  31658. if (offset >= totalIndices) {
  31659. break;
  31660. }
  31661. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31662. offset += subdivisionSize;
  31663. }
  31664. this.synchronizeInstances();
  31665. };
  31666. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31667. if (updatable === void 0) { updatable = false; }
  31668. if (!this._geometry) {
  31669. var vertexData = new BABYLON.VertexData();
  31670. vertexData.set(data, kind);
  31671. var scene = this.getScene();
  31672. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31673. }
  31674. else {
  31675. this._geometry.setVerticesData(kind, data, updatable, stride);
  31676. }
  31677. return this;
  31678. };
  31679. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31680. if (updatable === void 0) { updatable = true; }
  31681. var vb = this.getVertexBuffer(kind);
  31682. if (!vb || vb.isUpdatable() === updatable) {
  31683. return;
  31684. }
  31685. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31686. };
  31687. /**
  31688. * Sets the mesh VertexBuffer.
  31689. * Returns the Mesh.
  31690. */
  31691. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31692. if (!this._geometry) {
  31693. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31694. }
  31695. this._geometry.setVerticesBuffer(buffer);
  31696. return this;
  31697. };
  31698. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31699. if (!this._geometry) {
  31700. return this;
  31701. }
  31702. if (!makeItUnique) {
  31703. this._geometry.updateVerticesData(kind, data, updateExtends);
  31704. }
  31705. else {
  31706. this.makeGeometryUnique();
  31707. this.updateVerticesData(kind, data, updateExtends, false);
  31708. }
  31709. return this;
  31710. };
  31711. /**
  31712. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31713. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31714. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31715. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31716. * Returns the Mesh.
  31717. */
  31718. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31719. if (computeNormals === void 0) { computeNormals = true; }
  31720. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31721. if (!positions) {
  31722. return this;
  31723. }
  31724. positionFunction(positions);
  31725. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31726. if (computeNormals) {
  31727. var indices = this.getIndices();
  31728. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31729. if (!normals) {
  31730. return this;
  31731. }
  31732. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31733. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31734. }
  31735. return this;
  31736. };
  31737. /**
  31738. * Creates a un-shared specific occurence of the geometry for the mesh.
  31739. * Returns the Mesh.
  31740. */
  31741. Mesh.prototype.makeGeometryUnique = function () {
  31742. if (!this._geometry) {
  31743. return this;
  31744. }
  31745. var oldGeometry = this._geometry;
  31746. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31747. oldGeometry.releaseForMesh(this, true);
  31748. geometry.applyToMesh(this);
  31749. return this;
  31750. };
  31751. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31752. if (totalVertices === void 0) { totalVertices = null; }
  31753. if (updatable === void 0) { updatable = false; }
  31754. if (!this._geometry) {
  31755. var vertexData = new BABYLON.VertexData();
  31756. vertexData.indices = indices;
  31757. var scene = this.getScene();
  31758. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31759. }
  31760. else {
  31761. this._geometry.setIndices(indices, totalVertices, updatable);
  31762. }
  31763. return this;
  31764. };
  31765. /**
  31766. * Update the current index buffer
  31767. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31768. * Returns the Mesh.
  31769. */
  31770. Mesh.prototype.updateIndices = function (indices, offset) {
  31771. if (!this._geometry) {
  31772. return this;
  31773. }
  31774. this._geometry.updateIndices(indices, offset);
  31775. return this;
  31776. };
  31777. /**
  31778. * Invert the geometry to move from a right handed system to a left handed one.
  31779. * Returns the Mesh.
  31780. */
  31781. Mesh.prototype.toLeftHanded = function () {
  31782. if (!this._geometry) {
  31783. return this;
  31784. }
  31785. this._geometry.toLeftHanded();
  31786. return this;
  31787. };
  31788. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31789. if (!this._geometry) {
  31790. return this;
  31791. }
  31792. var engine = this.getScene().getEngine();
  31793. // Wireframe
  31794. var indexToBind;
  31795. if (this._unIndexed) {
  31796. indexToBind = null;
  31797. }
  31798. else {
  31799. switch (fillMode) {
  31800. case BABYLON.Material.PointFillMode:
  31801. indexToBind = null;
  31802. break;
  31803. case BABYLON.Material.WireFrameFillMode:
  31804. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31805. break;
  31806. default:
  31807. case BABYLON.Material.TriangleFillMode:
  31808. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31809. break;
  31810. }
  31811. }
  31812. // VBOs
  31813. this._geometry._bind(effect, indexToBind);
  31814. return this;
  31815. };
  31816. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31817. if (alternate === void 0) { alternate = false; }
  31818. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31819. return this;
  31820. }
  31821. this.onBeforeDrawObservable.notifyObservers(this);
  31822. var scene = this.getScene();
  31823. var engine = scene.getEngine();
  31824. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31825. // or triangles as points
  31826. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31827. }
  31828. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31829. // Triangles as wireframe
  31830. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31831. }
  31832. else {
  31833. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31834. }
  31835. if (scene._isAlternateRenderingEnabled && !alternate) {
  31836. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31837. if (!effect || !scene.activeCamera) {
  31838. return this;
  31839. }
  31840. scene._switchToAlternateCameraConfiguration(true);
  31841. this._effectiveMaterial.bindView(effect);
  31842. this._effectiveMaterial.bindViewProjection(effect);
  31843. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31844. this._draw(subMesh, fillMode, instancesCount, true);
  31845. engine.setViewport(scene.activeCamera.viewport);
  31846. scene._switchToAlternateCameraConfiguration(false);
  31847. this._effectiveMaterial.bindView(effect);
  31848. this._effectiveMaterial.bindViewProjection(effect);
  31849. }
  31850. return this;
  31851. };
  31852. /**
  31853. * Registers for this mesh a javascript function called just before the rendering process.
  31854. * This function is passed the current mesh.
  31855. * Return the Mesh.
  31856. */
  31857. Mesh.prototype.registerBeforeRender = function (func) {
  31858. this.onBeforeRenderObservable.add(func);
  31859. return this;
  31860. };
  31861. /**
  31862. * Disposes a previously registered javascript function called before the rendering.
  31863. * This function is passed the current mesh.
  31864. * Returns the Mesh.
  31865. */
  31866. Mesh.prototype.unregisterBeforeRender = function (func) {
  31867. this.onBeforeRenderObservable.removeCallback(func);
  31868. return this;
  31869. };
  31870. /**
  31871. * Registers for this mesh a javascript function called just after the rendering is complete.
  31872. * This function is passed the current mesh.
  31873. * Returns the Mesh.
  31874. */
  31875. Mesh.prototype.registerAfterRender = function (func) {
  31876. this.onAfterRenderObservable.add(func);
  31877. return this;
  31878. };
  31879. /**
  31880. * Disposes a previously registered javascript function called after the rendering.
  31881. * This function is passed the current mesh.
  31882. * Return the Mesh.
  31883. */
  31884. Mesh.prototype.unregisterAfterRender = function (func) {
  31885. this.onAfterRenderObservable.removeCallback(func);
  31886. return this;
  31887. };
  31888. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31889. var scene = this.getScene();
  31890. this._batchCache.mustReturn = false;
  31891. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31892. this._batchCache.visibleInstances[subMeshId] = null;
  31893. if (this._visibleInstances) {
  31894. var currentRenderId = scene.getRenderId();
  31895. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31896. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31897. var selfRenderId = this._renderId;
  31898. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31899. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31900. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31901. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31902. }
  31903. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31904. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31905. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31906. this._batchCache.mustReturn = true;
  31907. return this._batchCache;
  31908. }
  31909. if (currentRenderId !== selfRenderId) {
  31910. this._batchCache.renderSelf[subMeshId] = false;
  31911. }
  31912. }
  31913. this._renderIdForInstances[subMeshId] = currentRenderId;
  31914. }
  31915. return this._batchCache;
  31916. };
  31917. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31918. var visibleInstances = batch.visibleInstances[subMesh._id];
  31919. if (!visibleInstances) {
  31920. return this;
  31921. }
  31922. var matricesCount = visibleInstances.length + 1;
  31923. var bufferSize = matricesCount * 16 * 4;
  31924. var currentInstancesBufferSize = this._instancesBufferSize;
  31925. var instancesBuffer = this._instancesBuffer;
  31926. while (this._instancesBufferSize < bufferSize) {
  31927. this._instancesBufferSize *= 2;
  31928. }
  31929. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31930. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31931. }
  31932. var offset = 0;
  31933. var instancesCount = 0;
  31934. var world = this.getWorldMatrix();
  31935. if (batch.renderSelf[subMesh._id]) {
  31936. world.copyToArray(this._instancesData, offset);
  31937. offset += 16;
  31938. instancesCount++;
  31939. }
  31940. if (visibleInstances) {
  31941. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31942. var instance = visibleInstances[instanceIndex];
  31943. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31944. offset += 16;
  31945. instancesCount++;
  31946. }
  31947. }
  31948. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31949. if (instancesBuffer) {
  31950. instancesBuffer.dispose();
  31951. }
  31952. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31953. this._instancesBuffer = instancesBuffer;
  31954. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31955. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31956. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31957. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31958. }
  31959. else {
  31960. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31961. }
  31962. this._bind(subMesh, effect, fillMode);
  31963. this._draw(subMesh, fillMode, instancesCount);
  31964. engine.unbindInstanceAttributes();
  31965. return this;
  31966. };
  31967. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31968. var scene = this.getScene();
  31969. var engine = scene.getEngine();
  31970. if (hardwareInstancedRendering) {
  31971. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31972. }
  31973. else {
  31974. if (batch.renderSelf[subMesh._id]) {
  31975. // Draw
  31976. if (onBeforeDraw) {
  31977. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31978. }
  31979. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31980. }
  31981. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31982. if (visibleInstancesForSubMesh) {
  31983. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31984. var instance = visibleInstancesForSubMesh[instanceIndex];
  31985. // World
  31986. var world = instance.getWorldMatrix();
  31987. if (onBeforeDraw) {
  31988. onBeforeDraw(true, world, effectiveMaterial);
  31989. }
  31990. // Draw
  31991. this._draw(subMesh, fillMode);
  31992. }
  31993. }
  31994. }
  31995. return this;
  31996. };
  31997. /**
  31998. * Triggers the draw call for the mesh.
  31999. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32000. * Returns the Mesh.
  32001. */
  32002. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32003. this._checkOcclusionQuery();
  32004. if (this._isOccluded) {
  32005. return this;
  32006. }
  32007. var scene = this.getScene();
  32008. // Managing instances
  32009. var batch = this._getInstancesRenderList(subMesh._id);
  32010. if (batch.mustReturn) {
  32011. return this;
  32012. }
  32013. // Checking geometry state
  32014. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32015. return this;
  32016. }
  32017. this.onBeforeRenderObservable.notifyObservers(this);
  32018. var engine = scene.getEngine();
  32019. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32020. // Material
  32021. var material = subMesh.getMaterial();
  32022. if (!material) {
  32023. return this;
  32024. }
  32025. this._effectiveMaterial = material;
  32026. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32027. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32028. return this;
  32029. }
  32030. }
  32031. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32032. return this;
  32033. }
  32034. // Alpha mode
  32035. if (enableAlphaMode) {
  32036. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32037. }
  32038. // Outline - step 1
  32039. var savedDepthWrite = engine.getDepthWrite();
  32040. if (this.renderOutline) {
  32041. engine.setDepthWrite(false);
  32042. scene.getOutlineRenderer().render(subMesh, batch);
  32043. engine.setDepthWrite(savedDepthWrite);
  32044. }
  32045. var effect;
  32046. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32047. effect = subMesh.effect;
  32048. }
  32049. else {
  32050. effect = this._effectiveMaterial.getEffect();
  32051. }
  32052. if (!effect) {
  32053. return this;
  32054. }
  32055. var sideOrientation = this.overrideMaterialSideOrientation;
  32056. if (sideOrientation == null) {
  32057. sideOrientation = this._effectiveMaterial.sideOrientation;
  32058. if (this._getWorldMatrixDeterminant() < 0) {
  32059. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32060. }
  32061. }
  32062. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32063. if (this._effectiveMaterial.forceDepthWrite) {
  32064. engine.setDepthWrite(true);
  32065. }
  32066. // Bind
  32067. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32068. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32069. this._bind(subMesh, effect, fillMode);
  32070. }
  32071. var world = this.getWorldMatrix();
  32072. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32073. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32074. }
  32075. else {
  32076. this._effectiveMaterial.bind(world, this);
  32077. }
  32078. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32079. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32080. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32081. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32082. }
  32083. // Draw
  32084. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32085. // Unbind
  32086. this._effectiveMaterial.unbind();
  32087. // Outline - step 2
  32088. if (this.renderOutline && savedDepthWrite) {
  32089. engine.setDepthWrite(true);
  32090. engine.setColorWrite(false);
  32091. scene.getOutlineRenderer().render(subMesh, batch);
  32092. engine.setColorWrite(true);
  32093. }
  32094. // Overlay
  32095. if (this.renderOverlay) {
  32096. var currentMode = engine.getAlphaMode();
  32097. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32098. scene.getOutlineRenderer().render(subMesh, batch, true);
  32099. engine.setAlphaMode(currentMode);
  32100. }
  32101. this.onAfterRenderObservable.notifyObservers(this);
  32102. return this;
  32103. };
  32104. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32105. if (isInstance && effectiveMaterial) {
  32106. effectiveMaterial.bindOnlyWorldMatrix(world);
  32107. }
  32108. };
  32109. /**
  32110. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32111. */
  32112. Mesh.prototype.getEmittedParticleSystems = function () {
  32113. var results = new Array();
  32114. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32115. var particleSystem = this.getScene().particleSystems[index];
  32116. if (particleSystem.emitter === this) {
  32117. results.push(particleSystem);
  32118. }
  32119. }
  32120. return results;
  32121. };
  32122. /**
  32123. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32124. */
  32125. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32126. var results = new Array();
  32127. var descendants = this.getDescendants();
  32128. descendants.push(this);
  32129. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32130. var particleSystem = this.getScene().particleSystems[index];
  32131. var emitter = particleSystem.emitter;
  32132. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32133. results.push(particleSystem);
  32134. }
  32135. }
  32136. return results;
  32137. };
  32138. Mesh.prototype._checkDelayState = function () {
  32139. var scene = this.getScene();
  32140. if (this._geometry) {
  32141. this._geometry.load(scene);
  32142. }
  32143. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32144. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32145. this._queueLoad(scene);
  32146. }
  32147. return this;
  32148. };
  32149. Mesh.prototype._queueLoad = function (scene) {
  32150. var _this = this;
  32151. scene._addPendingData(this);
  32152. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32153. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32154. if (data instanceof ArrayBuffer) {
  32155. _this._delayLoadingFunction(data, _this);
  32156. }
  32157. else {
  32158. _this._delayLoadingFunction(JSON.parse(data), _this);
  32159. }
  32160. _this.instances.forEach(function (instance) {
  32161. instance._syncSubMeshes();
  32162. });
  32163. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32164. scene._removePendingData(_this);
  32165. }, function () { }, scene.database, getBinaryData);
  32166. return this;
  32167. };
  32168. /**
  32169. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32170. */
  32171. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32172. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32173. return false;
  32174. }
  32175. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32176. return false;
  32177. }
  32178. this._checkDelayState();
  32179. return true;
  32180. };
  32181. /**
  32182. * Sets the mesh material by the material or multiMaterial `id` property.
  32183. * The material `id` is a string identifying the material or the multiMaterial.
  32184. * This method returns the Mesh.
  32185. */
  32186. Mesh.prototype.setMaterialByID = function (id) {
  32187. var materials = this.getScene().materials;
  32188. var index;
  32189. for (index = materials.length - 1; index > -1; index--) {
  32190. if (materials[index].id === id) {
  32191. this.material = materials[index];
  32192. return this;
  32193. }
  32194. }
  32195. // Multi
  32196. var multiMaterials = this.getScene().multiMaterials;
  32197. for (index = multiMaterials.length - 1; index > -1; index--) {
  32198. if (multiMaterials[index].id === id) {
  32199. this.material = multiMaterials[index];
  32200. return this;
  32201. }
  32202. }
  32203. return this;
  32204. };
  32205. /**
  32206. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32207. */
  32208. Mesh.prototype.getAnimatables = function () {
  32209. var results = new Array();
  32210. if (this.material) {
  32211. results.push(this.material);
  32212. }
  32213. if (this.skeleton) {
  32214. results.push(this.skeleton);
  32215. }
  32216. return results;
  32217. };
  32218. /**
  32219. * Modifies the mesh geometry according to the passed transformation matrix.
  32220. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32221. * The mesh normals are modified accordingly the same transformation.
  32222. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32223. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32224. * Returns the Mesh.
  32225. */
  32226. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32227. // Position
  32228. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32229. return this;
  32230. }
  32231. var submeshes = this.subMeshes.splice(0);
  32232. this._resetPointsArrayCache();
  32233. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32234. var temp = new Array();
  32235. var index;
  32236. for (index = 0; index < data.length; index += 3) {
  32237. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32238. }
  32239. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32240. // Normals
  32241. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32242. return this;
  32243. }
  32244. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32245. temp = [];
  32246. for (index = 0; index < data.length; index += 3) {
  32247. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32248. }
  32249. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32250. // flip faces?
  32251. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32252. this.flipFaces();
  32253. }
  32254. // Restore submeshes
  32255. this.releaseSubMeshes();
  32256. this.subMeshes = submeshes;
  32257. return this;
  32258. };
  32259. /**
  32260. * Modifies the mesh geometry according to its own current World Matrix.
  32261. * The mesh World Matrix is then reset.
  32262. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32263. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32264. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32265. * Returns the Mesh.
  32266. */
  32267. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32268. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32269. this.scaling.copyFromFloats(1, 1, 1);
  32270. this.position.copyFromFloats(0, 0, 0);
  32271. this.rotation.copyFromFloats(0, 0, 0);
  32272. //only if quaternion is already set
  32273. if (this.rotationQuaternion) {
  32274. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32275. }
  32276. this._worldMatrix = BABYLON.Matrix.Identity();
  32277. return this;
  32278. };
  32279. Object.defineProperty(Mesh.prototype, "_positions", {
  32280. // Cache
  32281. get: function () {
  32282. if (this._geometry) {
  32283. return this._geometry._positions;
  32284. }
  32285. return null;
  32286. },
  32287. enumerable: true,
  32288. configurable: true
  32289. });
  32290. Mesh.prototype._resetPointsArrayCache = function () {
  32291. if (this._geometry) {
  32292. this._geometry._resetPointsArrayCache();
  32293. }
  32294. return this;
  32295. };
  32296. Mesh.prototype._generatePointsArray = function () {
  32297. if (this._geometry) {
  32298. return this._geometry._generatePointsArray();
  32299. }
  32300. return false;
  32301. };
  32302. /**
  32303. * Returns a new Mesh object generated from the current mesh properties.
  32304. * This method must not get confused with createInstance().
  32305. * The parameter `name` is a string, the name given to the new mesh.
  32306. * The optional parameter `newParent` can be any Node object (default `null`).
  32307. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32308. * 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.
  32309. */
  32310. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32311. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32312. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32313. };
  32314. /**
  32315. * Releases resources associated with this mesh.
  32316. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32317. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32318. */
  32319. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32320. var _this = this;
  32321. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32322. this.morphTargetManager = null;
  32323. if (this._geometry) {
  32324. this._geometry.releaseForMesh(this, true);
  32325. }
  32326. // Sources
  32327. var meshes = this.getScene().meshes;
  32328. meshes.forEach(function (abstractMesh) {
  32329. var mesh = abstractMesh;
  32330. if (mesh._source && mesh._source === _this) {
  32331. mesh._source = null;
  32332. }
  32333. });
  32334. this._source = null;
  32335. // Instances
  32336. if (this._instancesBuffer) {
  32337. this._instancesBuffer.dispose();
  32338. this._instancesBuffer = null;
  32339. }
  32340. while (this.instances.length) {
  32341. this.instances[0].dispose();
  32342. }
  32343. // Effect layers.
  32344. var effectLayers = this.getScene().effectLayers;
  32345. for (var i = 0; i < effectLayers.length; i++) {
  32346. var effectLayer = effectLayers[i];
  32347. if (effectLayer) {
  32348. effectLayer._disposeMesh(this);
  32349. }
  32350. }
  32351. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32352. };
  32353. /**
  32354. * Modifies the mesh geometry according to a displacement map.
  32355. * 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.
  32356. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32357. * This method returns nothing.
  32358. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32359. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32360. * 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.
  32361. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32362. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32363. *
  32364. * Returns the Mesh.
  32365. */
  32366. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32367. var _this = this;
  32368. var scene = this.getScene();
  32369. var onload = function (img) {
  32370. // Getting height map data
  32371. var canvas = document.createElement("canvas");
  32372. var context = canvas.getContext("2d");
  32373. var heightMapWidth = img.width;
  32374. var heightMapHeight = img.height;
  32375. canvas.width = heightMapWidth;
  32376. canvas.height = heightMapHeight;
  32377. context.drawImage(img, 0, 0);
  32378. // Create VertexData from map data
  32379. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32380. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32381. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32382. //execute success callback, if set
  32383. if (onSuccess) {
  32384. onSuccess(_this);
  32385. }
  32386. };
  32387. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32388. return this;
  32389. };
  32390. /**
  32391. * Modifies the mesh geometry according to a displacementMap buffer.
  32392. * 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.
  32393. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32394. * This method returns nothing.
  32395. * 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.
  32396. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32397. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32398. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32399. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32400. *
  32401. * Returns the Mesh.
  32402. */
  32403. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32404. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32405. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32406. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32407. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32408. return this;
  32409. }
  32410. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32411. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32412. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32413. var position = BABYLON.Vector3.Zero();
  32414. var normal = BABYLON.Vector3.Zero();
  32415. var uv = BABYLON.Vector2.Zero();
  32416. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32417. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32418. for (var index = 0; index < positions.length; index += 3) {
  32419. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32420. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32421. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32422. // Compute height
  32423. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32424. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32425. var pos = (u + v * heightMapWidth) * 4;
  32426. var r = buffer[pos] / 255.0;
  32427. var g = buffer[pos + 1] / 255.0;
  32428. var b = buffer[pos + 2] / 255.0;
  32429. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32430. normal.normalize();
  32431. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32432. position = position.add(normal);
  32433. position.toArray(positions, index);
  32434. }
  32435. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32436. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32437. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32438. return this;
  32439. };
  32440. /**
  32441. * Modify the mesh to get a flat shading rendering.
  32442. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32443. * This method returns the Mesh.
  32444. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32445. */
  32446. Mesh.prototype.convertToFlatShadedMesh = function () {
  32447. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32448. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32449. var kinds = this.getVerticesDataKinds();
  32450. var vbs = {};
  32451. var data = {};
  32452. var newdata = {};
  32453. var updatableNormals = false;
  32454. var kindIndex;
  32455. var kind;
  32456. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32457. kind = kinds[kindIndex];
  32458. var vertexBuffer = this.getVertexBuffer(kind);
  32459. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32460. updatableNormals = vertexBuffer.isUpdatable();
  32461. kinds.splice(kindIndex, 1);
  32462. kindIndex--;
  32463. continue;
  32464. }
  32465. vbs[kind] = vertexBuffer;
  32466. data[kind] = vbs[kind].getData();
  32467. newdata[kind] = [];
  32468. }
  32469. // Save previous submeshes
  32470. var previousSubmeshes = this.subMeshes.slice(0);
  32471. var indices = this.getIndices();
  32472. var totalIndices = this.getTotalIndices();
  32473. // Generating unique vertices per face
  32474. var index;
  32475. for (index = 0; index < totalIndices; index++) {
  32476. var vertexIndex = indices[index];
  32477. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32478. kind = kinds[kindIndex];
  32479. var stride = vbs[kind].getStrideSize();
  32480. for (var offset = 0; offset < stride; offset++) {
  32481. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32482. }
  32483. }
  32484. }
  32485. // Updating faces & normal
  32486. var normals = [];
  32487. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32488. for (index = 0; index < totalIndices; index += 3) {
  32489. indices[index] = index;
  32490. indices[index + 1] = index + 1;
  32491. indices[index + 2] = index + 2;
  32492. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32493. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32494. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32495. var p1p2 = p1.subtract(p2);
  32496. var p3p2 = p3.subtract(p2);
  32497. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32498. // Store same normals for every vertex
  32499. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32500. normals.push(normal.x);
  32501. normals.push(normal.y);
  32502. normals.push(normal.z);
  32503. }
  32504. }
  32505. this.setIndices(indices);
  32506. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32507. // Updating vertex buffers
  32508. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32509. kind = kinds[kindIndex];
  32510. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32511. }
  32512. // Updating submeshes
  32513. this.releaseSubMeshes();
  32514. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32515. var previousOne = previousSubmeshes[submeshIndex];
  32516. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32517. }
  32518. this.synchronizeInstances();
  32519. return this;
  32520. };
  32521. /**
  32522. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32523. * In other words, more vertices, no more indices and a single bigger VBO.
  32524. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32525. * Returns the Mesh.
  32526. */
  32527. Mesh.prototype.convertToUnIndexedMesh = function () {
  32528. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32529. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32530. var kinds = this.getVerticesDataKinds();
  32531. var vbs = {};
  32532. var data = {};
  32533. var newdata = {};
  32534. var kindIndex;
  32535. var kind;
  32536. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32537. kind = kinds[kindIndex];
  32538. var vertexBuffer = this.getVertexBuffer(kind);
  32539. vbs[kind] = vertexBuffer;
  32540. data[kind] = vbs[kind].getData();
  32541. newdata[kind] = [];
  32542. }
  32543. // Save previous submeshes
  32544. var previousSubmeshes = this.subMeshes.slice(0);
  32545. var indices = this.getIndices();
  32546. var totalIndices = this.getTotalIndices();
  32547. // Generating unique vertices per face
  32548. var index;
  32549. for (index = 0; index < totalIndices; index++) {
  32550. var vertexIndex = indices[index];
  32551. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32552. kind = kinds[kindIndex];
  32553. var stride = vbs[kind].getStrideSize();
  32554. for (var offset = 0; offset < stride; offset++) {
  32555. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32556. }
  32557. }
  32558. }
  32559. // Updating indices
  32560. for (index = 0; index < totalIndices; index += 3) {
  32561. indices[index] = index;
  32562. indices[index + 1] = index + 1;
  32563. indices[index + 2] = index + 2;
  32564. }
  32565. this.setIndices(indices);
  32566. // Updating vertex buffers
  32567. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32568. kind = kinds[kindIndex];
  32569. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32570. }
  32571. // Updating submeshes
  32572. this.releaseSubMeshes();
  32573. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32574. var previousOne = previousSubmeshes[submeshIndex];
  32575. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32576. }
  32577. this._unIndexed = true;
  32578. this.synchronizeInstances();
  32579. return this;
  32580. };
  32581. /**
  32582. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32583. * This method returns the Mesh.
  32584. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32585. */
  32586. Mesh.prototype.flipFaces = function (flipNormals) {
  32587. if (flipNormals === void 0) { flipNormals = false; }
  32588. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32589. var i;
  32590. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32591. for (i = 0; i < vertex_data.normals.length; i++) {
  32592. vertex_data.normals[i] *= -1;
  32593. }
  32594. }
  32595. if (vertex_data.indices) {
  32596. var temp;
  32597. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32598. // reassign indices
  32599. temp = vertex_data.indices[i + 1];
  32600. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32601. vertex_data.indices[i + 2] = temp;
  32602. }
  32603. }
  32604. vertex_data.applyToMesh(this);
  32605. return this;
  32606. };
  32607. // Instances
  32608. /**
  32609. * Creates a new InstancedMesh object from the mesh model.
  32610. * An instance shares the same properties and the same material than its model.
  32611. * Only these properties of each instance can then be set individually :
  32612. * - position
  32613. * - rotation
  32614. * - rotationQuaternion
  32615. * - setPivotMatrix
  32616. * - scaling
  32617. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32618. * Warning : this method is not supported for Line mesh and LineSystem
  32619. */
  32620. Mesh.prototype.createInstance = function (name) {
  32621. return new BABYLON.InstancedMesh(name, this);
  32622. };
  32623. /**
  32624. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32625. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32626. * This method returns the Mesh.
  32627. */
  32628. Mesh.prototype.synchronizeInstances = function () {
  32629. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32630. var instance = this.instances[instanceIndex];
  32631. instance._syncSubMeshes();
  32632. }
  32633. return this;
  32634. };
  32635. /**
  32636. * Simplify the mesh according to the given array of settings.
  32637. * Function will return immediately and will simplify async. It returns the Mesh.
  32638. * @param settings a collection of simplification settings.
  32639. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32640. * @param type the type of simplification to run.
  32641. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32642. */
  32643. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32644. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32645. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32646. this.getScene().simplificationQueue.addTask({
  32647. settings: settings,
  32648. parallelProcessing: parallelProcessing,
  32649. mesh: this,
  32650. simplificationType: simplificationType,
  32651. successCallback: successCallback
  32652. });
  32653. return this;
  32654. };
  32655. /**
  32656. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32657. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32658. * This should be used together with the simplification to avoid disappearing triangles.
  32659. * Returns the Mesh.
  32660. * @param successCallback an optional success callback to be called after the optimization finished.
  32661. */
  32662. Mesh.prototype.optimizeIndices = function (successCallback) {
  32663. var _this = this;
  32664. var indices = this.getIndices();
  32665. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32666. if (!positions || !indices) {
  32667. return this;
  32668. }
  32669. var vectorPositions = new Array();
  32670. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32671. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32672. }
  32673. var dupes = new Array();
  32674. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32675. var realPos = vectorPositions.length - 1 - iteration;
  32676. var testedPosition = vectorPositions[realPos];
  32677. for (var j = 0; j < realPos; ++j) {
  32678. var againstPosition = vectorPositions[j];
  32679. if (testedPosition.equals(againstPosition)) {
  32680. dupes[realPos] = j;
  32681. break;
  32682. }
  32683. }
  32684. }, function () {
  32685. for (var i = 0; i < indices.length; ++i) {
  32686. indices[i] = dupes[indices[i]] || indices[i];
  32687. }
  32688. //indices are now reordered
  32689. var originalSubMeshes = _this.subMeshes.slice(0);
  32690. _this.setIndices(indices);
  32691. _this.subMeshes = originalSubMeshes;
  32692. if (successCallback) {
  32693. successCallback(_this);
  32694. }
  32695. });
  32696. return this;
  32697. };
  32698. Mesh.prototype.serialize = function (serializationObject) {
  32699. serializationObject.name = this.name;
  32700. serializationObject.id = this.id;
  32701. serializationObject.type = this.getClassName();
  32702. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32703. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32704. }
  32705. serializationObject.position = this.position.asArray();
  32706. if (this.rotationQuaternion) {
  32707. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32708. }
  32709. else if (this.rotation) {
  32710. serializationObject.rotation = this.rotation.asArray();
  32711. }
  32712. serializationObject.scaling = this.scaling.asArray();
  32713. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32714. serializationObject.isEnabled = this.isEnabled(false);
  32715. serializationObject.isVisible = this.isVisible;
  32716. serializationObject.infiniteDistance = this.infiniteDistance;
  32717. serializationObject.pickable = this.isPickable;
  32718. serializationObject.receiveShadows = this.receiveShadows;
  32719. serializationObject.billboardMode = this.billboardMode;
  32720. serializationObject.visibility = this.visibility;
  32721. serializationObject.checkCollisions = this.checkCollisions;
  32722. serializationObject.isBlocker = this.isBlocker;
  32723. // Parent
  32724. if (this.parent) {
  32725. serializationObject.parentId = this.parent.id;
  32726. }
  32727. // Geometry
  32728. serializationObject.isUnIndexed = this.isUnIndexed;
  32729. var geometry = this._geometry;
  32730. if (geometry) {
  32731. var geometryId = geometry.id;
  32732. serializationObject.geometryId = geometryId;
  32733. // SubMeshes
  32734. serializationObject.subMeshes = [];
  32735. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32736. var subMesh = this.subMeshes[subIndex];
  32737. serializationObject.subMeshes.push({
  32738. materialIndex: subMesh.materialIndex,
  32739. verticesStart: subMesh.verticesStart,
  32740. verticesCount: subMesh.verticesCount,
  32741. indexStart: subMesh.indexStart,
  32742. indexCount: subMesh.indexCount
  32743. });
  32744. }
  32745. }
  32746. // Material
  32747. if (this.material) {
  32748. serializationObject.materialId = this.material.id;
  32749. }
  32750. else {
  32751. this.material = null;
  32752. }
  32753. // Morph targets
  32754. if (this.morphTargetManager) {
  32755. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32756. }
  32757. // Skeleton
  32758. if (this.skeleton) {
  32759. serializationObject.skeletonId = this.skeleton.id;
  32760. }
  32761. // Physics
  32762. //TODO implement correct serialization for physics impostors.
  32763. var impostor = this.getPhysicsImpostor();
  32764. if (impostor) {
  32765. serializationObject.physicsMass = impostor.getParam("mass");
  32766. serializationObject.physicsFriction = impostor.getParam("friction");
  32767. serializationObject.physicsRestitution = impostor.getParam("mass");
  32768. serializationObject.physicsImpostor = impostor.type;
  32769. }
  32770. // Metadata
  32771. if (this.metadata) {
  32772. serializationObject.metadata = this.metadata;
  32773. }
  32774. // Instances
  32775. serializationObject.instances = [];
  32776. for (var index = 0; index < this.instances.length; index++) {
  32777. var instance = this.instances[index];
  32778. var serializationInstance = {
  32779. name: instance.name,
  32780. id: instance.id,
  32781. position: instance.position.asArray(),
  32782. scaling: instance.scaling.asArray()
  32783. };
  32784. if (instance.rotationQuaternion) {
  32785. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32786. }
  32787. else if (instance.rotation) {
  32788. serializationInstance.rotation = instance.rotation.asArray();
  32789. }
  32790. serializationObject.instances.push(serializationInstance);
  32791. // Animations
  32792. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32793. serializationInstance.ranges = instance.serializeAnimationRanges();
  32794. }
  32795. //
  32796. // Animations
  32797. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32798. serializationObject.ranges = this.serializeAnimationRanges();
  32799. // Layer mask
  32800. serializationObject.layerMask = this.layerMask;
  32801. // Alpha
  32802. serializationObject.alphaIndex = this.alphaIndex;
  32803. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32804. // Overlay
  32805. serializationObject.overlayAlpha = this.overlayAlpha;
  32806. serializationObject.overlayColor = this.overlayColor.asArray();
  32807. serializationObject.renderOverlay = this.renderOverlay;
  32808. // Fog
  32809. serializationObject.applyFog = this.applyFog;
  32810. // Action Manager
  32811. if (this.actionManager) {
  32812. serializationObject.actions = this.actionManager.serialize(this.name);
  32813. }
  32814. };
  32815. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32816. if (!this.geometry) {
  32817. return;
  32818. }
  32819. this._markSubMeshesAsAttributesDirty();
  32820. var morphTargetManager = this._morphTargetManager;
  32821. if (morphTargetManager && morphTargetManager.vertexCount) {
  32822. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32823. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32824. this.morphTargetManager = null;
  32825. return;
  32826. }
  32827. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32828. var morphTarget = morphTargetManager.getActiveTarget(index);
  32829. var positions = morphTarget.getPositions();
  32830. if (!positions) {
  32831. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32832. return;
  32833. }
  32834. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32835. var normals = morphTarget.getNormals();
  32836. if (normals) {
  32837. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32838. }
  32839. var tangents = morphTarget.getTangents();
  32840. if (tangents) {
  32841. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32842. }
  32843. }
  32844. }
  32845. else {
  32846. var index = 0;
  32847. // Positions
  32848. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32849. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32850. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32851. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32852. }
  32853. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32854. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32855. }
  32856. index++;
  32857. }
  32858. }
  32859. };
  32860. // Statics
  32861. /**
  32862. * Returns a new Mesh object parsed from the source provided.
  32863. * The parameter `parsedMesh` is the source.
  32864. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32865. */
  32866. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32867. var mesh;
  32868. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32869. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32870. }
  32871. else {
  32872. mesh = new Mesh(parsedMesh.name, scene);
  32873. }
  32874. mesh.id = parsedMesh.id;
  32875. if (BABYLON.Tags) {
  32876. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32877. }
  32878. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32879. if (parsedMesh.metadata !== undefined) {
  32880. mesh.metadata = parsedMesh.metadata;
  32881. }
  32882. if (parsedMesh.rotationQuaternion) {
  32883. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32884. }
  32885. else if (parsedMesh.rotation) {
  32886. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32887. }
  32888. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32889. if (parsedMesh.localMatrix) {
  32890. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32891. }
  32892. else if (parsedMesh.pivotMatrix) {
  32893. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32894. }
  32895. mesh.setEnabled(parsedMesh.isEnabled);
  32896. mesh.isVisible = parsedMesh.isVisible;
  32897. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32898. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32899. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32900. if (parsedMesh.applyFog !== undefined) {
  32901. mesh.applyFog = parsedMesh.applyFog;
  32902. }
  32903. if (parsedMesh.pickable !== undefined) {
  32904. mesh.isPickable = parsedMesh.pickable;
  32905. }
  32906. if (parsedMesh.alphaIndex !== undefined) {
  32907. mesh.alphaIndex = parsedMesh.alphaIndex;
  32908. }
  32909. mesh.receiveShadows = parsedMesh.receiveShadows;
  32910. mesh.billboardMode = parsedMesh.billboardMode;
  32911. if (parsedMesh.visibility !== undefined) {
  32912. mesh.visibility = parsedMesh.visibility;
  32913. }
  32914. mesh.checkCollisions = parsedMesh.checkCollisions;
  32915. if (parsedMesh.isBlocker !== undefined) {
  32916. mesh.isBlocker = parsedMesh.isBlocker;
  32917. }
  32918. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32919. // freezeWorldMatrix
  32920. if (parsedMesh.freezeWorldMatrix) {
  32921. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32922. }
  32923. // Parent
  32924. if (parsedMesh.parentId) {
  32925. mesh._waitingParentId = parsedMesh.parentId;
  32926. }
  32927. // Actions
  32928. if (parsedMesh.actions !== undefined) {
  32929. mesh._waitingActions = parsedMesh.actions;
  32930. }
  32931. // Overlay
  32932. if (parsedMesh.overlayAlpha !== undefined) {
  32933. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32934. }
  32935. if (parsedMesh.overlayColor !== undefined) {
  32936. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32937. }
  32938. if (parsedMesh.renderOverlay !== undefined) {
  32939. mesh.renderOverlay = parsedMesh.renderOverlay;
  32940. }
  32941. // Geometry
  32942. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32943. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32944. if (parsedMesh.delayLoadingFile) {
  32945. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32946. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32947. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32948. if (parsedMesh._binaryInfo) {
  32949. mesh._binaryInfo = parsedMesh._binaryInfo;
  32950. }
  32951. mesh._delayInfo = [];
  32952. if (parsedMesh.hasUVs) {
  32953. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32954. }
  32955. if (parsedMesh.hasUVs2) {
  32956. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32957. }
  32958. if (parsedMesh.hasUVs3) {
  32959. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32960. }
  32961. if (parsedMesh.hasUVs4) {
  32962. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32963. }
  32964. if (parsedMesh.hasUVs5) {
  32965. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32966. }
  32967. if (parsedMesh.hasUVs6) {
  32968. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32969. }
  32970. if (parsedMesh.hasColors) {
  32971. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32972. }
  32973. if (parsedMesh.hasMatricesIndices) {
  32974. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32975. }
  32976. if (parsedMesh.hasMatricesWeights) {
  32977. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32978. }
  32979. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32980. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32981. mesh._checkDelayState();
  32982. }
  32983. }
  32984. else {
  32985. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32986. }
  32987. // Material
  32988. if (parsedMesh.materialId) {
  32989. mesh.setMaterialByID(parsedMesh.materialId);
  32990. }
  32991. else {
  32992. mesh.material = null;
  32993. }
  32994. // Morph targets
  32995. if (parsedMesh.morphTargetManagerId > -1) {
  32996. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32997. }
  32998. // Skeleton
  32999. if (parsedMesh.skeletonId > -1) {
  33000. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33001. if (parsedMesh.numBoneInfluencers) {
  33002. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33003. }
  33004. }
  33005. // Animations
  33006. if (parsedMesh.animations) {
  33007. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33008. var parsedAnimation = parsedMesh.animations[animationIndex];
  33009. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33010. }
  33011. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33012. }
  33013. if (parsedMesh.autoAnimate) {
  33014. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33015. }
  33016. // Layer Mask
  33017. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33018. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33019. }
  33020. else {
  33021. mesh.layerMask = 0x0FFFFFFF;
  33022. }
  33023. // Physics
  33024. if (parsedMesh.physicsImpostor) {
  33025. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33026. mass: parsedMesh.physicsMass,
  33027. friction: parsedMesh.physicsFriction,
  33028. restitution: parsedMesh.physicsRestitution
  33029. }, scene);
  33030. }
  33031. // Instances
  33032. if (parsedMesh.instances) {
  33033. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33034. var parsedInstance = parsedMesh.instances[index];
  33035. var instance = mesh.createInstance(parsedInstance.name);
  33036. if (parsedInstance.id) {
  33037. instance.id = parsedInstance.id;
  33038. }
  33039. if (BABYLON.Tags) {
  33040. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33041. }
  33042. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33043. if (parsedInstance.parentId) {
  33044. instance._waitingParentId = parsedInstance.parentId;
  33045. }
  33046. if (parsedInstance.rotationQuaternion) {
  33047. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33048. }
  33049. else if (parsedInstance.rotation) {
  33050. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33051. }
  33052. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33053. instance.checkCollisions = mesh.checkCollisions;
  33054. if (parsedMesh.animations) {
  33055. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33056. parsedAnimation = parsedMesh.animations[animationIndex];
  33057. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33058. }
  33059. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33060. }
  33061. }
  33062. }
  33063. return mesh;
  33064. };
  33065. /**
  33066. * Creates a ribbon mesh.
  33067. * Please consider using the same method from the MeshBuilder class instead.
  33068. * 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.
  33069. *
  33070. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33071. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33072. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33073. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33074. * 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.
  33075. * 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.
  33076. * 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
  33077. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33078. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33079. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33080. */
  33081. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33082. if (closeArray === void 0) { closeArray = false; }
  33083. if (updatable === void 0) { updatable = false; }
  33084. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33085. pathArray: pathArray,
  33086. closeArray: closeArray,
  33087. closePath: closePath,
  33088. offset: offset,
  33089. updatable: updatable,
  33090. sideOrientation: sideOrientation,
  33091. instance: instance
  33092. }, scene);
  33093. };
  33094. /**
  33095. * Creates a plane polygonal mesh. By default, this is a disc.
  33096. * Please consider using the same method from the MeshBuilder class instead.
  33097. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33098. * 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.
  33099. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33100. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33102. */
  33103. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33104. if (scene === void 0) { scene = null; }
  33105. var options = {
  33106. radius: radius,
  33107. tessellation: tessellation,
  33108. sideOrientation: sideOrientation,
  33109. updatable: updatable
  33110. };
  33111. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33112. };
  33113. /**
  33114. * Creates a box mesh.
  33115. * Please consider using the same method from the MeshBuilder class instead.
  33116. * The parameter `size` sets the size (float) of each box side (default 1).
  33117. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33118. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33119. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33120. */
  33121. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33122. if (scene === void 0) { scene = null; }
  33123. var options = {
  33124. size: size,
  33125. sideOrientation: sideOrientation,
  33126. updatable: updatable
  33127. };
  33128. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33129. };
  33130. /**
  33131. * Creates a sphere mesh.
  33132. * Please consider using the same method from the MeshBuilder class instead.
  33133. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33134. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33135. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33136. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33138. */
  33139. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33140. var options = {
  33141. segments: segments,
  33142. diameterX: diameter,
  33143. diameterY: diameter,
  33144. diameterZ: diameter,
  33145. sideOrientation: sideOrientation,
  33146. updatable: updatable
  33147. };
  33148. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33149. };
  33150. /**
  33151. * Creates a cylinder or a cone mesh.
  33152. * Please consider using the same method from the MeshBuilder class instead.
  33153. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33154. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33155. * 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.
  33156. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33157. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33158. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33159. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33161. */
  33162. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33163. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33164. if (scene !== undefined) {
  33165. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33166. updatable = scene;
  33167. }
  33168. scene = subdivisions;
  33169. subdivisions = 1;
  33170. }
  33171. var options = {
  33172. height: height,
  33173. diameterTop: diameterTop,
  33174. diameterBottom: diameterBottom,
  33175. tessellation: tessellation,
  33176. subdivisions: subdivisions,
  33177. sideOrientation: sideOrientation,
  33178. updatable: updatable
  33179. };
  33180. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33181. };
  33182. // Torus (Code from SharpDX.org)
  33183. /**
  33184. * Creates a torus mesh.
  33185. * Please consider using the same method from the MeshBuilder class instead.
  33186. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33187. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33188. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33189. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33190. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33191. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33192. */
  33193. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33194. var options = {
  33195. diameter: diameter,
  33196. thickness: thickness,
  33197. tessellation: tessellation,
  33198. sideOrientation: sideOrientation,
  33199. updatable: updatable
  33200. };
  33201. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33202. };
  33203. /**
  33204. * Creates a torus knot mesh.
  33205. * Please consider using the same method from the MeshBuilder class instead.
  33206. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33207. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33208. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33209. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33210. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33211. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33212. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33213. */
  33214. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33215. var options = {
  33216. radius: radius,
  33217. tube: tube,
  33218. radialSegments: radialSegments,
  33219. tubularSegments: tubularSegments,
  33220. p: p,
  33221. q: q,
  33222. sideOrientation: sideOrientation,
  33223. updatable: updatable
  33224. };
  33225. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33226. };
  33227. /**
  33228. * Creates a line mesh.
  33229. * Please consider using the same method from the MeshBuilder class instead.
  33230. * 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.
  33231. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33232. * The parameter `points` is an array successive Vector3.
  33233. * 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
  33234. * When updating an instance, remember that only point positions can change, not the number of points.
  33235. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33236. */
  33237. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33238. if (scene === void 0) { scene = null; }
  33239. if (updatable === void 0) { updatable = false; }
  33240. if (instance === void 0) { instance = null; }
  33241. var options = {
  33242. points: points,
  33243. updatable: updatable,
  33244. instance: instance
  33245. };
  33246. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33247. };
  33248. /**
  33249. * Creates a dashed line mesh.
  33250. * Please consider using the same method from the MeshBuilder class instead.
  33251. * 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.
  33252. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33253. * The parameter `points` is an array successive Vector3.
  33254. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33255. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33256. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33257. * 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
  33258. * When updating an instance, remember that only point positions can change, not the number of points.
  33259. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33260. */
  33261. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33262. if (scene === void 0) { scene = null; }
  33263. var options = {
  33264. points: points,
  33265. dashSize: dashSize,
  33266. gapSize: gapSize,
  33267. dashNb: dashNb,
  33268. updatable: updatable,
  33269. instance: instance
  33270. };
  33271. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33272. };
  33273. /**
  33274. * Creates a polygon mesh.
  33275. * Please consider using the same method from the MeshBuilder class instead.
  33276. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33277. * 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.
  33278. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33279. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33280. * Remember you can only change the shape positions, not their number when updating a polygon.
  33281. */
  33282. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33283. var options = {
  33284. shape: shape,
  33285. holes: holes,
  33286. updatable: updatable,
  33287. sideOrientation: sideOrientation
  33288. };
  33289. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33290. };
  33291. /**
  33292. * Creates an extruded polygon mesh, with depth in the Y direction.
  33293. * Please consider using the same method from the MeshBuilder class instead.
  33294. */
  33295. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33296. var options = {
  33297. shape: shape,
  33298. holes: holes,
  33299. depth: depth,
  33300. updatable: updatable,
  33301. sideOrientation: sideOrientation
  33302. };
  33303. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33304. };
  33305. /**
  33306. * Creates an extruded shape mesh.
  33307. * 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.
  33308. * Please consider using the same method from the MeshBuilder class instead.
  33309. *
  33310. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33311. * 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
  33312. * extruded along the Z axis.
  33313. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33314. * 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.
  33315. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33316. * 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
  33317. * 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
  33318. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33319. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33320. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33321. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33322. */
  33323. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33324. if (scene === void 0) { scene = null; }
  33325. var options = {
  33326. shape: shape,
  33327. path: path,
  33328. scale: scale,
  33329. rotation: rotation,
  33330. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33331. sideOrientation: sideOrientation,
  33332. instance: instance,
  33333. updatable: updatable
  33334. };
  33335. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33336. };
  33337. /**
  33338. * Creates an custom extruded shape mesh.
  33339. * 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.
  33340. * Please consider using the same method from the MeshBuilder class instead.
  33341. *
  33342. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33343. * 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
  33344. * extruded along the Z axis.
  33345. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33346. * 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
  33347. * and the distance of this point from the begining of the path :
  33348. * ```javascript
  33349. * var rotationFunction = function(i, distance) {
  33350. * // do things
  33351. * return rotationValue; }
  33352. * ```
  33353. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33354. * 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
  33355. * and the distance of this point from the begining of the path :
  33356. * ```javascript
  33357. * var scaleFunction = function(i, distance) {
  33358. * // do things
  33359. * return scaleValue;}
  33360. * ```
  33361. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33362. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33363. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33364. * 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
  33365. * 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
  33366. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33367. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33368. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33369. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33370. */
  33371. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33372. var options = {
  33373. shape: shape,
  33374. path: path,
  33375. scaleFunction: scaleFunction,
  33376. rotationFunction: rotationFunction,
  33377. ribbonCloseArray: ribbonCloseArray,
  33378. ribbonClosePath: ribbonClosePath,
  33379. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33380. sideOrientation: sideOrientation,
  33381. instance: instance,
  33382. updatable: updatable
  33383. };
  33384. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33385. };
  33386. /**
  33387. * Creates lathe mesh.
  33388. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33389. * Please consider using the same method from the MeshBuilder class instead.
  33390. * 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
  33391. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33392. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33393. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33395. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33397. */
  33398. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33399. var options = {
  33400. shape: shape,
  33401. radius: radius,
  33402. tessellation: tessellation,
  33403. sideOrientation: sideOrientation,
  33404. updatable: updatable
  33405. };
  33406. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33407. };
  33408. /**
  33409. * Creates a plane mesh.
  33410. * Please consider using the same method from the MeshBuilder class instead.
  33411. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33412. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33413. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33414. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33415. */
  33416. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33417. var options = {
  33418. size: size,
  33419. width: size,
  33420. height: size,
  33421. sideOrientation: sideOrientation,
  33422. updatable: updatable
  33423. };
  33424. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33425. };
  33426. /**
  33427. * Creates a ground mesh.
  33428. * Please consider using the same method from the MeshBuilder class instead.
  33429. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33430. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33432. */
  33433. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33434. var options = {
  33435. width: width,
  33436. height: height,
  33437. subdivisions: subdivisions,
  33438. updatable: updatable
  33439. };
  33440. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33441. };
  33442. /**
  33443. * Creates a tiled ground mesh.
  33444. * Please consider using the same method from the MeshBuilder class instead.
  33445. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33446. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33447. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33448. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33449. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33450. * numbers of subdivisions on the ground width and height of each tile.
  33451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33452. */
  33453. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33454. var options = {
  33455. xmin: xmin,
  33456. zmin: zmin,
  33457. xmax: xmax,
  33458. zmax: zmax,
  33459. subdivisions: subdivisions,
  33460. precision: precision,
  33461. updatable: updatable
  33462. };
  33463. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33464. };
  33465. /**
  33466. * Creates a ground mesh from a height map.
  33467. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33468. * Please consider using the same method from the MeshBuilder class instead.
  33469. * The parameter `url` sets the URL of the height map image resource.
  33470. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33471. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33472. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33473. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33474. * 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).
  33475. * This function is passed the newly built mesh :
  33476. * ```javascript
  33477. * function(mesh) { // do things
  33478. * return; }
  33479. * ```
  33480. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33481. */
  33482. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33483. var options = {
  33484. width: width,
  33485. height: height,
  33486. subdivisions: subdivisions,
  33487. minHeight: minHeight,
  33488. maxHeight: maxHeight,
  33489. updatable: updatable,
  33490. onReady: onReady
  33491. };
  33492. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33493. };
  33494. /**
  33495. * Creates a tube mesh.
  33496. * 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.
  33497. * Please consider using the same method from the MeshBuilder class instead.
  33498. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33499. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33500. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33501. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33502. * 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.
  33503. * It must return a radius value (positive float) :
  33504. * ```javascript
  33505. * var radiusFunction = function(i, distance) {
  33506. * // do things
  33507. * return radius; }
  33508. * ```
  33509. * 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
  33510. * 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
  33511. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33512. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33514. */
  33515. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33516. var options = {
  33517. path: path,
  33518. radius: radius,
  33519. tessellation: tessellation,
  33520. radiusFunction: radiusFunction,
  33521. arc: 1,
  33522. cap: cap,
  33523. updatable: updatable,
  33524. sideOrientation: sideOrientation,
  33525. instance: instance
  33526. };
  33527. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33528. };
  33529. /**
  33530. * Creates a polyhedron mesh.
  33531. * Please consider using the same method from the MeshBuilder class instead.
  33532. * 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
  33533. * to choose the wanted type.
  33534. * The parameter `size` (positive float, default 1) sets the polygon size.
  33535. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33536. * 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`.
  33537. * 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
  33538. * 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)`).
  33539. * 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
  33540. * 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.
  33541. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33542. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33544. */
  33545. Mesh.CreatePolyhedron = function (name, options, scene) {
  33546. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33547. };
  33548. /**
  33549. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33550. * Please consider using the same method from the MeshBuilder class instead.
  33551. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33552. * 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`).
  33553. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33554. * 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.
  33555. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33556. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33557. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33558. */
  33559. Mesh.CreateIcoSphere = function (name, options, scene) {
  33560. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33561. };
  33562. /**
  33563. * Creates a decal mesh.
  33564. * Please consider using the same method from the MeshBuilder class instead.
  33565. * 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.
  33566. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33567. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33568. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33569. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33570. */
  33571. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33572. var options = {
  33573. position: position,
  33574. normal: normal,
  33575. size: size,
  33576. angle: angle
  33577. };
  33578. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33579. };
  33580. // Skeletons
  33581. /**
  33582. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33583. */
  33584. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33585. if (!this._sourcePositions) {
  33586. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33587. if (!source) {
  33588. return this._sourcePositions;
  33589. }
  33590. this._sourcePositions = new Float32Array(source);
  33591. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33592. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33593. }
  33594. }
  33595. return this._sourcePositions;
  33596. };
  33597. /**
  33598. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33599. */
  33600. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33601. if (!this._sourceNormals) {
  33602. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33603. if (!source) {
  33604. return this._sourceNormals;
  33605. }
  33606. this._sourceNormals = new Float32Array(source);
  33607. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33608. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33609. }
  33610. }
  33611. return this._sourceNormals;
  33612. };
  33613. /**
  33614. * Updates the vertex buffer by applying transformation from the bones.
  33615. * Returns the Mesh.
  33616. *
  33617. * @param {skeleton} skeleton to apply
  33618. */
  33619. Mesh.prototype.applySkeleton = function (skeleton) {
  33620. if (!this.geometry) {
  33621. return this;
  33622. }
  33623. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33624. return this;
  33625. }
  33626. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33627. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33628. return this;
  33629. }
  33630. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33631. return this;
  33632. }
  33633. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33634. return this;
  33635. }
  33636. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33637. return this;
  33638. }
  33639. if (!this._sourcePositions) {
  33640. var submeshes = this.subMeshes.slice();
  33641. this.setPositionsForCPUSkinning();
  33642. this.subMeshes = submeshes;
  33643. }
  33644. if (!this._sourceNormals) {
  33645. this.setNormalsForCPUSkinning();
  33646. }
  33647. // positionsData checks for not being Float32Array will only pass at most once
  33648. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33649. if (!positionsData) {
  33650. return this;
  33651. }
  33652. if (!(positionsData instanceof Float32Array)) {
  33653. positionsData = new Float32Array(positionsData);
  33654. }
  33655. // normalsData checks for not being Float32Array will only pass at most once
  33656. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33657. if (!normalsData) {
  33658. return this;
  33659. }
  33660. if (!(normalsData instanceof Float32Array)) {
  33661. normalsData = new Float32Array(normalsData);
  33662. }
  33663. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33664. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33665. if (!matricesWeightsData || !matricesIndicesData) {
  33666. return this;
  33667. }
  33668. var needExtras = this.numBoneInfluencers > 4;
  33669. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33670. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33671. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33672. var tempVector3 = BABYLON.Vector3.Zero();
  33673. var finalMatrix = new BABYLON.Matrix();
  33674. var tempMatrix = new BABYLON.Matrix();
  33675. var matWeightIdx = 0;
  33676. var inf;
  33677. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33678. var weight;
  33679. for (inf = 0; inf < 4; inf++) {
  33680. weight = matricesWeightsData[matWeightIdx + inf];
  33681. if (weight > 0) {
  33682. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33683. finalMatrix.addToSelf(tempMatrix);
  33684. }
  33685. else
  33686. break;
  33687. }
  33688. if (needExtras) {
  33689. for (inf = 0; inf < 4; inf++) {
  33690. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33691. if (weight > 0) {
  33692. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33693. finalMatrix.addToSelf(tempMatrix);
  33694. }
  33695. else
  33696. break;
  33697. }
  33698. }
  33699. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33700. tempVector3.toArray(positionsData, index);
  33701. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33702. tempVector3.toArray(normalsData, index);
  33703. finalMatrix.reset();
  33704. }
  33705. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33706. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33707. return this;
  33708. };
  33709. // Tools
  33710. /**
  33711. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33712. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33713. */
  33714. Mesh.MinMax = function (meshes) {
  33715. var minVector = null;
  33716. var maxVector = null;
  33717. meshes.forEach(function (mesh, index, array) {
  33718. var boundingInfo = mesh.getBoundingInfo();
  33719. var boundingBox = boundingInfo.boundingBox;
  33720. if (!minVector || !maxVector) {
  33721. minVector = boundingBox.minimumWorld;
  33722. maxVector = boundingBox.maximumWorld;
  33723. }
  33724. else {
  33725. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33726. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33727. }
  33728. });
  33729. if (!minVector || !maxVector) {
  33730. return {
  33731. min: BABYLON.Vector3.Zero(),
  33732. max: BABYLON.Vector3.Zero()
  33733. };
  33734. }
  33735. return {
  33736. min: minVector,
  33737. max: maxVector
  33738. };
  33739. };
  33740. /**
  33741. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33742. */
  33743. Mesh.Center = function (meshesOrMinMaxVector) {
  33744. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33745. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33746. };
  33747. /**
  33748. * Merge the array of meshes into a single mesh for performance reasons.
  33749. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33750. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33751. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33752. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33753. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33754. */
  33755. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33756. if (disposeSource === void 0) { disposeSource = true; }
  33757. var index;
  33758. if (!allow32BitsIndices) {
  33759. var totalVertices = 0;
  33760. // Counting vertices
  33761. for (index = 0; index < meshes.length; index++) {
  33762. if (meshes[index]) {
  33763. totalVertices += meshes[index].getTotalVertices();
  33764. if (totalVertices > 65536) {
  33765. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33766. return null;
  33767. }
  33768. }
  33769. }
  33770. }
  33771. // Merge
  33772. var vertexData = null;
  33773. var otherVertexData;
  33774. var indiceArray = new Array();
  33775. var source = null;
  33776. for (index = 0; index < meshes.length; index++) {
  33777. if (meshes[index]) {
  33778. meshes[index].computeWorldMatrix(true);
  33779. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33780. otherVertexData.transform(meshes[index].getWorldMatrix());
  33781. if (vertexData) {
  33782. vertexData.merge(otherVertexData);
  33783. }
  33784. else {
  33785. vertexData = otherVertexData;
  33786. source = meshes[index];
  33787. }
  33788. if (subdivideWithSubMeshes) {
  33789. indiceArray.push(meshes[index].getTotalIndices());
  33790. }
  33791. }
  33792. }
  33793. source = source;
  33794. if (!meshSubclass) {
  33795. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33796. }
  33797. vertexData.applyToMesh(meshSubclass);
  33798. // Setting properties
  33799. meshSubclass.material = source.material;
  33800. meshSubclass.checkCollisions = source.checkCollisions;
  33801. // Cleaning
  33802. if (disposeSource) {
  33803. for (index = 0; index < meshes.length; index++) {
  33804. if (meshes[index]) {
  33805. meshes[index].dispose();
  33806. }
  33807. }
  33808. }
  33809. // Subdivide
  33810. if (subdivideWithSubMeshes) {
  33811. //-- Suppresions du submesh global
  33812. meshSubclass.releaseSubMeshes();
  33813. index = 0;
  33814. var offset = 0;
  33815. //-- aplique la subdivision en fonction du tableau d'indices
  33816. while (index < indiceArray.length) {
  33817. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33818. offset += indiceArray[index];
  33819. index++;
  33820. }
  33821. }
  33822. return meshSubclass;
  33823. };
  33824. // Consts
  33825. Mesh._FRONTSIDE = 0;
  33826. Mesh._BACKSIDE = 1;
  33827. Mesh._DOUBLESIDE = 2;
  33828. Mesh._DEFAULTSIDE = 0;
  33829. Mesh._NO_CAP = 0;
  33830. Mesh._CAP_START = 1;
  33831. Mesh._CAP_END = 2;
  33832. Mesh._CAP_ALL = 3;
  33833. return Mesh;
  33834. }(BABYLON.AbstractMesh));
  33835. BABYLON.Mesh = Mesh;
  33836. })(BABYLON || (BABYLON = {}));
  33837. //# sourceMappingURL=babylon.mesh.js.map
  33838. var BABYLON;
  33839. (function (BABYLON) {
  33840. var BaseSubMesh = /** @class */ (function () {
  33841. function BaseSubMesh() {
  33842. }
  33843. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33844. get: function () {
  33845. return this._materialEffect;
  33846. },
  33847. enumerable: true,
  33848. configurable: true
  33849. });
  33850. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33851. if (defines === void 0) { defines = null; }
  33852. if (this._materialEffect === effect) {
  33853. if (!effect) {
  33854. this._materialDefines = null;
  33855. }
  33856. return;
  33857. }
  33858. this._materialDefines = defines;
  33859. this._materialEffect = effect;
  33860. };
  33861. return BaseSubMesh;
  33862. }());
  33863. BABYLON.BaseSubMesh = BaseSubMesh;
  33864. var SubMesh = /** @class */ (function (_super) {
  33865. __extends(SubMesh, _super);
  33866. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33867. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33868. var _this = _super.call(this) || this;
  33869. _this.materialIndex = materialIndex;
  33870. _this.verticesStart = verticesStart;
  33871. _this.verticesCount = verticesCount;
  33872. _this.indexStart = indexStart;
  33873. _this.indexCount = indexCount;
  33874. _this._renderId = 0;
  33875. _this._mesh = mesh;
  33876. _this._renderingMesh = renderingMesh || mesh;
  33877. mesh.subMeshes.push(_this);
  33878. _this._trianglePlanes = [];
  33879. _this._id = mesh.subMeshes.length - 1;
  33880. if (createBoundingBox) {
  33881. _this.refreshBoundingInfo();
  33882. mesh.computeWorldMatrix(true);
  33883. }
  33884. return _this;
  33885. }
  33886. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33887. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33888. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33889. };
  33890. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33891. get: function () {
  33892. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33893. },
  33894. enumerable: true,
  33895. configurable: true
  33896. });
  33897. /**
  33898. * Returns the submesh BoudingInfo object.
  33899. */
  33900. SubMesh.prototype.getBoundingInfo = function () {
  33901. if (this.IsGlobal) {
  33902. return this._mesh.getBoundingInfo();
  33903. }
  33904. return this._boundingInfo;
  33905. };
  33906. /**
  33907. * Sets the submesh BoundingInfo.
  33908. * Return the SubMesh.
  33909. */
  33910. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33911. this._boundingInfo = boundingInfo;
  33912. return this;
  33913. };
  33914. /**
  33915. * Returns the mesh of the current submesh.
  33916. */
  33917. SubMesh.prototype.getMesh = function () {
  33918. return this._mesh;
  33919. };
  33920. /**
  33921. * Returns the rendering mesh of the submesh.
  33922. */
  33923. SubMesh.prototype.getRenderingMesh = function () {
  33924. return this._renderingMesh;
  33925. };
  33926. /**
  33927. * Returns the submesh material.
  33928. */
  33929. SubMesh.prototype.getMaterial = function () {
  33930. var rootMaterial = this._renderingMesh.material;
  33931. if (rootMaterial === null || rootMaterial === undefined) {
  33932. return this._mesh.getScene().defaultMaterial;
  33933. }
  33934. else if (rootMaterial.getSubMaterial) {
  33935. var multiMaterial = rootMaterial;
  33936. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33937. if (this._currentMaterial !== effectiveMaterial) {
  33938. this._currentMaterial = effectiveMaterial;
  33939. this._materialDefines = null;
  33940. }
  33941. return effectiveMaterial;
  33942. }
  33943. return rootMaterial;
  33944. };
  33945. // Methods
  33946. /**
  33947. * Sets a new updated BoundingInfo object to the submesh.
  33948. * Returns the SubMesh.
  33949. */
  33950. SubMesh.prototype.refreshBoundingInfo = function () {
  33951. this._lastColliderWorldVertices = null;
  33952. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33953. return this;
  33954. }
  33955. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33956. if (!data) {
  33957. this._boundingInfo = this._mesh.getBoundingInfo();
  33958. return this;
  33959. }
  33960. var indices = this._renderingMesh.getIndices();
  33961. var extend;
  33962. //is this the only submesh?
  33963. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33964. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33965. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33966. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33967. }
  33968. else {
  33969. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33970. }
  33971. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33972. return this;
  33973. };
  33974. SubMesh.prototype._checkCollision = function (collider) {
  33975. var boundingInfo = this.getBoundingInfo();
  33976. return boundingInfo._checkCollision(collider);
  33977. };
  33978. /**
  33979. * Updates the submesh BoundingInfo.
  33980. * Returns the Submesh.
  33981. */
  33982. SubMesh.prototype.updateBoundingInfo = function (world) {
  33983. var boundingInfo = this.getBoundingInfo();
  33984. if (!boundingInfo) {
  33985. this.refreshBoundingInfo();
  33986. boundingInfo = this.getBoundingInfo();
  33987. }
  33988. boundingInfo.update(world);
  33989. return this;
  33990. };
  33991. /**
  33992. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33993. * Boolean returned.
  33994. */
  33995. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33996. var boundingInfo = this.getBoundingInfo();
  33997. if (!boundingInfo) {
  33998. return false;
  33999. }
  34000. return boundingInfo.isInFrustum(frustumPlanes);
  34001. };
  34002. /**
  34003. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34004. * Boolean returned.
  34005. */
  34006. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34007. var boundingInfo = this.getBoundingInfo();
  34008. if (!boundingInfo) {
  34009. return false;
  34010. }
  34011. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34012. };
  34013. /**
  34014. * Renders the submesh.
  34015. * Returns it.
  34016. */
  34017. SubMesh.prototype.render = function (enableAlphaMode) {
  34018. this._renderingMesh.render(this, enableAlphaMode);
  34019. return this;
  34020. };
  34021. /**
  34022. * Returns a new Index Buffer.
  34023. * Type returned : WebGLBuffer.
  34024. */
  34025. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34026. if (!this._linesIndexBuffer) {
  34027. var linesIndices = [];
  34028. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34029. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34030. }
  34031. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34032. this.linesIndexCount = linesIndices.length;
  34033. }
  34034. return this._linesIndexBuffer;
  34035. };
  34036. /**
  34037. * True is the passed Ray intersects the submesh bounding box.
  34038. * Boolean returned.
  34039. */
  34040. SubMesh.prototype.canIntersects = function (ray) {
  34041. var boundingInfo = this.getBoundingInfo();
  34042. if (!boundingInfo) {
  34043. return false;
  34044. }
  34045. return ray.intersectsBox(boundingInfo.boundingBox);
  34046. };
  34047. /**
  34048. * Returns an object IntersectionInfo.
  34049. */
  34050. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34051. var intersectInfo = null;
  34052. var material = this.getMaterial();
  34053. if (!material) {
  34054. return null;
  34055. }
  34056. switch (material.fillMode) {
  34057. case BABYLON.Material.PointListDrawMode:
  34058. case BABYLON.Material.LineListDrawMode:
  34059. case BABYLON.Material.LineLoopDrawMode:
  34060. case BABYLON.Material.LineStripDrawMode:
  34061. case BABYLON.Material.TriangleFanDrawMode:
  34062. case BABYLON.Material.TriangleStripDrawMode:
  34063. return null;
  34064. }
  34065. // LineMesh first as it's also a Mesh...
  34066. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34067. var lineMesh = this._mesh;
  34068. // Line test
  34069. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34070. var p0 = positions[indices[index]];
  34071. var p1 = positions[indices[index + 1]];
  34072. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34073. if (length < 0) {
  34074. continue;
  34075. }
  34076. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34077. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34078. if (fastCheck) {
  34079. break;
  34080. }
  34081. }
  34082. }
  34083. }
  34084. else {
  34085. // Triangles test
  34086. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34087. var p0 = positions[indices[index]];
  34088. var p1 = positions[indices[index + 1]];
  34089. var p2 = positions[indices[index + 2]];
  34090. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34091. if (currentIntersectInfo) {
  34092. if (currentIntersectInfo.distance < 0) {
  34093. continue;
  34094. }
  34095. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34096. intersectInfo = currentIntersectInfo;
  34097. intersectInfo.faceId = index / 3;
  34098. if (fastCheck) {
  34099. break;
  34100. }
  34101. }
  34102. }
  34103. }
  34104. }
  34105. return intersectInfo;
  34106. };
  34107. SubMesh.prototype._rebuild = function () {
  34108. if (this._linesIndexBuffer) {
  34109. this._linesIndexBuffer = null;
  34110. }
  34111. };
  34112. // Clone
  34113. /**
  34114. * Creates a new Submesh from the passed Mesh.
  34115. */
  34116. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34117. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34118. if (!this.IsGlobal) {
  34119. var boundingInfo = this.getBoundingInfo();
  34120. if (!boundingInfo) {
  34121. return result;
  34122. }
  34123. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34124. }
  34125. return result;
  34126. };
  34127. // Dispose
  34128. /**
  34129. * Disposes the Submesh.
  34130. * Returns nothing.
  34131. */
  34132. SubMesh.prototype.dispose = function () {
  34133. if (this._linesIndexBuffer) {
  34134. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34135. this._linesIndexBuffer = null;
  34136. }
  34137. // Remove from mesh
  34138. var index = this._mesh.subMeshes.indexOf(this);
  34139. this._mesh.subMeshes.splice(index, 1);
  34140. };
  34141. // Statics
  34142. /**
  34143. * Creates a new Submesh from the passed parameters :
  34144. * - materialIndex (integer) : the index of the main mesh material.
  34145. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34146. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34147. * - mesh (Mesh) : the main mesh to create the submesh from.
  34148. * - renderingMesh (optional Mesh) : rendering mesh.
  34149. */
  34150. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34151. var minVertexIndex = Number.MAX_VALUE;
  34152. var maxVertexIndex = -Number.MAX_VALUE;
  34153. renderingMesh = (renderingMesh || mesh);
  34154. var indices = renderingMesh.getIndices();
  34155. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34156. var vertexIndex = indices[index];
  34157. if (vertexIndex < minVertexIndex)
  34158. minVertexIndex = vertexIndex;
  34159. if (vertexIndex > maxVertexIndex)
  34160. maxVertexIndex = vertexIndex;
  34161. }
  34162. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34163. };
  34164. return SubMesh;
  34165. }(BaseSubMesh));
  34166. BABYLON.SubMesh = SubMesh;
  34167. })(BABYLON || (BABYLON = {}));
  34168. //# sourceMappingURL=babylon.subMesh.js.map
  34169. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34170. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34171. s = arguments[i];
  34172. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34173. t[p] = s[p];
  34174. }
  34175. return t;
  34176. };
  34177. var BABYLON;
  34178. (function (BABYLON) {
  34179. /**
  34180. * Manages the defines for the Material
  34181. */
  34182. var MaterialDefines = /** @class */ (function () {
  34183. function MaterialDefines() {
  34184. this._isDirty = true;
  34185. /** @hidden */
  34186. this._areLightsDirty = true;
  34187. /** @hidden */
  34188. this._areAttributesDirty = true;
  34189. /** @hidden */
  34190. this._areTexturesDirty = true;
  34191. /** @hidden */
  34192. this._areFresnelDirty = true;
  34193. /** @hidden */
  34194. this._areMiscDirty = true;
  34195. /** @hidden */
  34196. this._areImageProcessingDirty = true;
  34197. /** @hidden */
  34198. this._normals = false;
  34199. /** @hidden */
  34200. this._uvs = false;
  34201. /** @hidden */
  34202. this._needNormals = false;
  34203. /** @hidden */
  34204. this._needUVs = false;
  34205. }
  34206. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34207. /**
  34208. * Specifies if the material needs to be re-calculated
  34209. */
  34210. get: function () {
  34211. return this._isDirty;
  34212. },
  34213. enumerable: true,
  34214. configurable: true
  34215. });
  34216. /**
  34217. * Marks the material to indicate that it has been re-calculated
  34218. */
  34219. MaterialDefines.prototype.markAsProcessed = function () {
  34220. this._isDirty = false;
  34221. this._areAttributesDirty = false;
  34222. this._areTexturesDirty = false;
  34223. this._areFresnelDirty = false;
  34224. this._areLightsDirty = false;
  34225. this._areMiscDirty = false;
  34226. this._areImageProcessingDirty = false;
  34227. };
  34228. /**
  34229. * Marks the material to indicate that it needs to be re-calculated
  34230. */
  34231. MaterialDefines.prototype.markAsUnprocessed = function () {
  34232. this._isDirty = true;
  34233. };
  34234. /**
  34235. * Marks the material to indicate all of its defines need to be re-calculated
  34236. */
  34237. MaterialDefines.prototype.markAllAsDirty = function () {
  34238. this._areTexturesDirty = true;
  34239. this._areAttributesDirty = true;
  34240. this._areLightsDirty = true;
  34241. this._areFresnelDirty = true;
  34242. this._areMiscDirty = true;
  34243. this._areImageProcessingDirty = true;
  34244. this._isDirty = true;
  34245. };
  34246. /**
  34247. * Marks the material to indicate that image processing needs to be re-calculated
  34248. */
  34249. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34250. this._areImageProcessingDirty = true;
  34251. this._isDirty = true;
  34252. };
  34253. /**
  34254. * Marks the material to indicate the lights need to be re-calculated
  34255. */
  34256. MaterialDefines.prototype.markAsLightDirty = function () {
  34257. this._areLightsDirty = true;
  34258. this._isDirty = true;
  34259. };
  34260. /**
  34261. * Marks the attribute state as changed
  34262. */
  34263. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34264. this._areAttributesDirty = true;
  34265. this._isDirty = true;
  34266. };
  34267. /**
  34268. * Marks the texture state as changed
  34269. */
  34270. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34271. this._areTexturesDirty = true;
  34272. this._isDirty = true;
  34273. };
  34274. /**
  34275. * Marks the fresnel state as changed
  34276. */
  34277. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34278. this._areFresnelDirty = true;
  34279. this._isDirty = true;
  34280. };
  34281. /**
  34282. * Marks the misc state as changed
  34283. */
  34284. MaterialDefines.prototype.markAsMiscDirty = function () {
  34285. this._areMiscDirty = true;
  34286. this._isDirty = true;
  34287. };
  34288. /**
  34289. * Rebuilds the material defines
  34290. */
  34291. MaterialDefines.prototype.rebuild = function () {
  34292. if (this._keys) {
  34293. delete this._keys;
  34294. }
  34295. this._keys = [];
  34296. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34297. var key = _a[_i];
  34298. if (key[0] === "_") {
  34299. continue;
  34300. }
  34301. this._keys.push(key);
  34302. }
  34303. };
  34304. /**
  34305. * Specifies if two material defines are equal
  34306. * @param other - A material define instance to compare to
  34307. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34308. */
  34309. MaterialDefines.prototype.isEqual = function (other) {
  34310. if (this._keys.length !== other._keys.length) {
  34311. return false;
  34312. }
  34313. for (var index = 0; index < this._keys.length; index++) {
  34314. var prop = this._keys[index];
  34315. if (this[prop] !== other[prop]) {
  34316. return false;
  34317. }
  34318. }
  34319. return true;
  34320. };
  34321. /**
  34322. * Clones this instance's defines to another instance
  34323. * @param other - material defines to clone values to
  34324. */
  34325. MaterialDefines.prototype.cloneTo = function (other) {
  34326. if (this._keys.length !== other._keys.length) {
  34327. other._keys = this._keys.slice(0);
  34328. }
  34329. for (var index = 0; index < this._keys.length; index++) {
  34330. var prop = this._keys[index];
  34331. other[prop] = this[prop];
  34332. }
  34333. };
  34334. /**
  34335. * Resets the material define values
  34336. */
  34337. MaterialDefines.prototype.reset = function () {
  34338. for (var index = 0; index < this._keys.length; index++) {
  34339. var prop = this._keys[index];
  34340. var type = typeof this[prop];
  34341. switch (type) {
  34342. case "number":
  34343. this[prop] = 0;
  34344. break;
  34345. case "string":
  34346. this[prop] = "";
  34347. break;
  34348. default:
  34349. this[prop] = false;
  34350. break;
  34351. }
  34352. }
  34353. };
  34354. /**
  34355. * Converts the material define values to a string
  34356. * @returns - String of material define information
  34357. */
  34358. MaterialDefines.prototype.toString = function () {
  34359. var result = "";
  34360. for (var index = 0; index < this._keys.length; index++) {
  34361. var prop = this._keys[index];
  34362. var value = this[prop];
  34363. var type = typeof value;
  34364. switch (type) {
  34365. case "number":
  34366. case "string":
  34367. result += "#define " + prop + " " + value + "\n";
  34368. break;
  34369. default:
  34370. if (value) {
  34371. result += "#define " + prop + "\n";
  34372. }
  34373. break;
  34374. }
  34375. }
  34376. return result;
  34377. };
  34378. return MaterialDefines;
  34379. }());
  34380. BABYLON.MaterialDefines = MaterialDefines;
  34381. /**
  34382. * Base class for the main features of a material in Babylon.js
  34383. */
  34384. var Material = /** @class */ (function () {
  34385. /**
  34386. * Creates a material instance
  34387. * @param name defines the name of the material
  34388. * @param scene defines the scene to reference
  34389. * @param doNotAdd specifies if the material should be added to the scene
  34390. */
  34391. function Material(name, scene, doNotAdd) {
  34392. /**
  34393. * Specifies if the ready state should be checked on each call
  34394. */
  34395. this.checkReadyOnEveryCall = false;
  34396. /**
  34397. * Specifies if the ready state should be checked once
  34398. */
  34399. this.checkReadyOnlyOnce = false;
  34400. /**
  34401. * The state of the material
  34402. */
  34403. this.state = "";
  34404. /**
  34405. * The alpha value of the material
  34406. */
  34407. this._alpha = 1.0;
  34408. /**
  34409. * Specifies if back face culling is enabled
  34410. */
  34411. this._backFaceCulling = true;
  34412. /**
  34413. * Specifies if the material should be serialized
  34414. */
  34415. this.doNotSerialize = false;
  34416. /**
  34417. * Specifies if the effect should be stored on sub meshes
  34418. */
  34419. this.storeEffectOnSubMeshes = false;
  34420. /**
  34421. * An event triggered when the material is disposed
  34422. */
  34423. this.onDisposeObservable = new BABYLON.Observable();
  34424. /**
  34425. * An event triggered when the material is bound
  34426. */
  34427. this.onBindObservable = new BABYLON.Observable();
  34428. /**
  34429. * An event triggered when the material is unbound
  34430. */
  34431. this.onUnBindObservable = new BABYLON.Observable();
  34432. /**
  34433. * Stores the value of the alpha mode
  34434. */
  34435. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34436. /**
  34437. * Stores the state of the need depth pre-pass value
  34438. */
  34439. this._needDepthPrePass = false;
  34440. /**
  34441. * Specifies if depth writing should be disabled
  34442. */
  34443. this.disableDepthWrite = false;
  34444. /**
  34445. * Specifies if depth writing should be forced
  34446. */
  34447. this.forceDepthWrite = false;
  34448. /**
  34449. * Specifies if there should be a separate pass for culling
  34450. */
  34451. this.separateCullingPass = false;
  34452. /**
  34453. * Stores the state specifing if fog should be enabled
  34454. */
  34455. this._fogEnabled = true;
  34456. /**
  34457. * Stores the size of points
  34458. */
  34459. this.pointSize = 1.0;
  34460. /**
  34461. * Stores the z offset value
  34462. */
  34463. this.zOffset = 0;
  34464. /**
  34465. * Specifies if the material was previously ready
  34466. */
  34467. this._wasPreviouslyReady = false;
  34468. /**
  34469. * Stores the fill mode state
  34470. */
  34471. this._fillMode = Material.TriangleFillMode;
  34472. this.name = name;
  34473. this.id = name || BABYLON.Tools.RandomId();
  34474. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34475. if (this._scene.useRightHandedSystem) {
  34476. this.sideOrientation = Material.ClockWiseSideOrientation;
  34477. }
  34478. else {
  34479. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34480. }
  34481. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34482. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34483. if (!doNotAdd) {
  34484. this._scene.materials.push(this);
  34485. }
  34486. }
  34487. Object.defineProperty(Material, "TriangleFillMode", {
  34488. /**
  34489. * Returns the triangle fill mode
  34490. */
  34491. get: function () {
  34492. return Material._TriangleFillMode;
  34493. },
  34494. enumerable: true,
  34495. configurable: true
  34496. });
  34497. Object.defineProperty(Material, "WireFrameFillMode", {
  34498. /**
  34499. * Returns the wireframe mode
  34500. */
  34501. get: function () {
  34502. return Material._WireFrameFillMode;
  34503. },
  34504. enumerable: true,
  34505. configurable: true
  34506. });
  34507. Object.defineProperty(Material, "PointFillMode", {
  34508. /**
  34509. * Returns the point fill mode
  34510. */
  34511. get: function () {
  34512. return Material._PointFillMode;
  34513. },
  34514. enumerable: true,
  34515. configurable: true
  34516. });
  34517. Object.defineProperty(Material, "PointListDrawMode", {
  34518. /**
  34519. * Returns the point list draw mode
  34520. */
  34521. get: function () {
  34522. return Material._PointListDrawMode;
  34523. },
  34524. enumerable: true,
  34525. configurable: true
  34526. });
  34527. Object.defineProperty(Material, "LineListDrawMode", {
  34528. /**
  34529. * Returns the line list draw mode
  34530. */
  34531. get: function () {
  34532. return Material._LineListDrawMode;
  34533. },
  34534. enumerable: true,
  34535. configurable: true
  34536. });
  34537. Object.defineProperty(Material, "LineLoopDrawMode", {
  34538. /**
  34539. * Returns the line loop draw mode
  34540. */
  34541. get: function () {
  34542. return Material._LineLoopDrawMode;
  34543. },
  34544. enumerable: true,
  34545. configurable: true
  34546. });
  34547. Object.defineProperty(Material, "LineStripDrawMode", {
  34548. /**
  34549. * Returns the line strip draw mode
  34550. */
  34551. get: function () {
  34552. return Material._LineStripDrawMode;
  34553. },
  34554. enumerable: true,
  34555. configurable: true
  34556. });
  34557. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34558. /**
  34559. * Returns the triangle strip draw mode
  34560. */
  34561. get: function () {
  34562. return Material._TriangleStripDrawMode;
  34563. },
  34564. enumerable: true,
  34565. configurable: true
  34566. });
  34567. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34568. /**
  34569. * Returns the triangle fan draw mode
  34570. */
  34571. get: function () {
  34572. return Material._TriangleFanDrawMode;
  34573. },
  34574. enumerable: true,
  34575. configurable: true
  34576. });
  34577. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34578. /**
  34579. * Returns the clock-wise side orientation
  34580. */
  34581. get: function () {
  34582. return Material._ClockWiseSideOrientation;
  34583. },
  34584. enumerable: true,
  34585. configurable: true
  34586. });
  34587. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34588. /**
  34589. * Returns the counter clock-wise side orientation
  34590. */
  34591. get: function () {
  34592. return Material._CounterClockWiseSideOrientation;
  34593. },
  34594. enumerable: true,
  34595. configurable: true
  34596. });
  34597. Object.defineProperty(Material, "TextureDirtyFlag", {
  34598. /**
  34599. * Returns the dirty texture flag value
  34600. */
  34601. get: function () {
  34602. return Material._TextureDirtyFlag;
  34603. },
  34604. enumerable: true,
  34605. configurable: true
  34606. });
  34607. Object.defineProperty(Material, "LightDirtyFlag", {
  34608. /**
  34609. * Returns the dirty light flag value
  34610. */
  34611. get: function () {
  34612. return Material._LightDirtyFlag;
  34613. },
  34614. enumerable: true,
  34615. configurable: true
  34616. });
  34617. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34618. /**
  34619. * Returns the dirty fresnel flag value
  34620. */
  34621. get: function () {
  34622. return Material._FresnelDirtyFlag;
  34623. },
  34624. enumerable: true,
  34625. configurable: true
  34626. });
  34627. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34628. /**
  34629. * Returns the dirty attributes flag value
  34630. */
  34631. get: function () {
  34632. return Material._AttributesDirtyFlag;
  34633. },
  34634. enumerable: true,
  34635. configurable: true
  34636. });
  34637. Object.defineProperty(Material, "MiscDirtyFlag", {
  34638. /**
  34639. * Returns the dirty misc flag value
  34640. */
  34641. get: function () {
  34642. return Material._MiscDirtyFlag;
  34643. },
  34644. enumerable: true,
  34645. configurable: true
  34646. });
  34647. Object.defineProperty(Material.prototype, "alpha", {
  34648. /**
  34649. * Gets the alpha value of the material
  34650. */
  34651. get: function () {
  34652. return this._alpha;
  34653. },
  34654. /**
  34655. * Sets the alpha value of the material
  34656. */
  34657. set: function (value) {
  34658. if (this._alpha === value) {
  34659. return;
  34660. }
  34661. this._alpha = value;
  34662. this.markAsDirty(Material.MiscDirtyFlag);
  34663. },
  34664. enumerable: true,
  34665. configurable: true
  34666. });
  34667. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34668. /**
  34669. * Gets the back-face culling state
  34670. */
  34671. get: function () {
  34672. return this._backFaceCulling;
  34673. },
  34674. /**
  34675. * Sets the back-face culling state
  34676. */
  34677. set: function (value) {
  34678. if (this._backFaceCulling === value) {
  34679. return;
  34680. }
  34681. this._backFaceCulling = value;
  34682. this.markAsDirty(Material.TextureDirtyFlag);
  34683. },
  34684. enumerable: true,
  34685. configurable: true
  34686. });
  34687. Object.defineProperty(Material.prototype, "onDispose", {
  34688. /**
  34689. * Called during a dispose event
  34690. */
  34691. set: function (callback) {
  34692. if (this._onDisposeObserver) {
  34693. this.onDisposeObservable.remove(this._onDisposeObserver);
  34694. }
  34695. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34696. },
  34697. enumerable: true,
  34698. configurable: true
  34699. });
  34700. Object.defineProperty(Material.prototype, "onBind", {
  34701. /**
  34702. * Called during a bind event
  34703. */
  34704. set: function (callback) {
  34705. if (this._onBindObserver) {
  34706. this.onBindObservable.remove(this._onBindObserver);
  34707. }
  34708. this._onBindObserver = this.onBindObservable.add(callback);
  34709. },
  34710. enumerable: true,
  34711. configurable: true
  34712. });
  34713. Object.defineProperty(Material.prototype, "alphaMode", {
  34714. /**
  34715. * Gets the value of the alpha mode
  34716. */
  34717. get: function () {
  34718. return this._alphaMode;
  34719. },
  34720. /**
  34721. * Sets the value of the alpha mode.
  34722. *
  34723. * | Value | Type | Description |
  34724. * | --- | --- | --- |
  34725. * | 0 | ALPHA_DISABLE | |
  34726. * | 1 | ALPHA_ADD | |
  34727. * | 2 | ALPHA_COMBINE | |
  34728. * | 3 | ALPHA_SUBTRACT | |
  34729. * | 4 | ALPHA_MULTIPLY | |
  34730. * | 5 | ALPHA_MAXIMIZED | |
  34731. * | 6 | ALPHA_ONEONE | |
  34732. * | 7 | ALPHA_PREMULTIPLIED | |
  34733. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34734. * | 9 | ALPHA_INTERPOLATE | |
  34735. * | 10 | ALPHA_SCREENMODE | |
  34736. *
  34737. */
  34738. set: function (value) {
  34739. if (this._alphaMode === value) {
  34740. return;
  34741. }
  34742. this._alphaMode = value;
  34743. this.markAsDirty(Material.TextureDirtyFlag);
  34744. },
  34745. enumerable: true,
  34746. configurable: true
  34747. });
  34748. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34749. /**
  34750. * Gets the depth pre-pass value
  34751. */
  34752. get: function () {
  34753. return this._needDepthPrePass;
  34754. },
  34755. /**
  34756. * Sets the need depth pre-pass value
  34757. */
  34758. set: function (value) {
  34759. if (this._needDepthPrePass === value) {
  34760. return;
  34761. }
  34762. this._needDepthPrePass = value;
  34763. if (this._needDepthPrePass) {
  34764. this.checkReadyOnEveryCall = true;
  34765. }
  34766. },
  34767. enumerable: true,
  34768. configurable: true
  34769. });
  34770. Object.defineProperty(Material.prototype, "fogEnabled", {
  34771. /**
  34772. * Gets the value of the fog enabled state
  34773. */
  34774. get: function () {
  34775. return this._fogEnabled;
  34776. },
  34777. /**
  34778. * Sets the state for enabling fog
  34779. */
  34780. set: function (value) {
  34781. if (this._fogEnabled === value) {
  34782. return;
  34783. }
  34784. this._fogEnabled = value;
  34785. this.markAsDirty(Material.MiscDirtyFlag);
  34786. },
  34787. enumerable: true,
  34788. configurable: true
  34789. });
  34790. Object.defineProperty(Material.prototype, "wireframe", {
  34791. /**
  34792. * Gets a value specifying if wireframe mode is enabled
  34793. */
  34794. get: function () {
  34795. switch (this._fillMode) {
  34796. case Material.WireFrameFillMode:
  34797. case Material.LineListDrawMode:
  34798. case Material.LineLoopDrawMode:
  34799. case Material.LineStripDrawMode:
  34800. return true;
  34801. }
  34802. return this._scene.forceWireframe;
  34803. },
  34804. /**
  34805. * Sets the state of wireframe mode
  34806. */
  34807. set: function (value) {
  34808. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34809. },
  34810. enumerable: true,
  34811. configurable: true
  34812. });
  34813. Object.defineProperty(Material.prototype, "pointsCloud", {
  34814. /**
  34815. * Gets the value specifying if point clouds are enabled
  34816. */
  34817. get: function () {
  34818. switch (this._fillMode) {
  34819. case Material.PointFillMode:
  34820. case Material.PointListDrawMode:
  34821. return true;
  34822. }
  34823. return this._scene.forcePointsCloud;
  34824. },
  34825. /**
  34826. * Sets the state of point cloud mode
  34827. */
  34828. set: function (value) {
  34829. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34830. },
  34831. enumerable: true,
  34832. configurable: true
  34833. });
  34834. Object.defineProperty(Material.prototype, "fillMode", {
  34835. /**
  34836. * Gets the material fill mode
  34837. */
  34838. get: function () {
  34839. return this._fillMode;
  34840. },
  34841. /**
  34842. * Sets the material fill mode
  34843. */
  34844. set: function (value) {
  34845. if (this._fillMode === value) {
  34846. return;
  34847. }
  34848. this._fillMode = value;
  34849. this.markAsDirty(Material.MiscDirtyFlag);
  34850. },
  34851. enumerable: true,
  34852. configurable: true
  34853. });
  34854. /**
  34855. * Returns a string representation of the current material
  34856. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34857. * @returns a string with material information
  34858. */
  34859. Material.prototype.toString = function (fullDetails) {
  34860. var ret = "Name: " + this.name;
  34861. if (fullDetails) {
  34862. }
  34863. return ret;
  34864. };
  34865. /**
  34866. * Gets the class name of the material
  34867. * @returns a string with the class name of the material
  34868. */
  34869. Material.prototype.getClassName = function () {
  34870. return "Material";
  34871. };
  34872. Object.defineProperty(Material.prototype, "isFrozen", {
  34873. /**
  34874. * Specifies if updates for the material been locked
  34875. */
  34876. get: function () {
  34877. return this.checkReadyOnlyOnce;
  34878. },
  34879. enumerable: true,
  34880. configurable: true
  34881. });
  34882. /**
  34883. * Locks updates for the material
  34884. */
  34885. Material.prototype.freeze = function () {
  34886. this.checkReadyOnlyOnce = true;
  34887. };
  34888. /**
  34889. * Unlocks updates for the material
  34890. */
  34891. Material.prototype.unfreeze = function () {
  34892. this.checkReadyOnlyOnce = false;
  34893. };
  34894. /**
  34895. * Specifies if the material is ready to be used
  34896. * @param mesh defines the mesh to check
  34897. * @param useInstances specifies if instances should be used
  34898. * @returns a boolean indicating if the material is ready to be used
  34899. */
  34900. Material.prototype.isReady = function (mesh, useInstances) {
  34901. return true;
  34902. };
  34903. /**
  34904. * Specifies that the submesh is ready to be used
  34905. * @param mesh defines the mesh to check
  34906. * @param subMesh defines which submesh to check
  34907. * @param useInstances specifies that instances should be used
  34908. * @returns a boolean indicating that the submesh is ready or not
  34909. */
  34910. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34911. return false;
  34912. };
  34913. /**
  34914. * Returns the material effect
  34915. * @returns the effect associated with the material
  34916. */
  34917. Material.prototype.getEffect = function () {
  34918. return this._effect;
  34919. };
  34920. /**
  34921. * Returns the current scene
  34922. * @returns a Scene
  34923. */
  34924. Material.prototype.getScene = function () {
  34925. return this._scene;
  34926. };
  34927. /**
  34928. * Specifies if the material will require alpha blending
  34929. * @returns a boolean specifying if alpha blending is needed
  34930. */
  34931. Material.prototype.needAlphaBlending = function () {
  34932. return (this.alpha < 1.0);
  34933. };
  34934. /**
  34935. * Specifies if the mesh will require alpha blending
  34936. * @param mesh defines the mesh to check
  34937. * @returns a boolean specifying if alpha blending is needed for the mesh
  34938. */
  34939. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34940. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34941. };
  34942. /**
  34943. * Specifies if this material should be rendered in alpha test mode
  34944. * @returns a boolean specifying if an alpha test is needed.
  34945. */
  34946. Material.prototype.needAlphaTesting = function () {
  34947. return false;
  34948. };
  34949. /**
  34950. * Gets the texture used for the alpha test
  34951. * @returns the texture to use for alpha testing
  34952. */
  34953. Material.prototype.getAlphaTestTexture = function () {
  34954. return null;
  34955. };
  34956. /**
  34957. * Marks the material to indicate that it needs to be re-calculated
  34958. */
  34959. Material.prototype.markDirty = function () {
  34960. this._wasPreviouslyReady = false;
  34961. };
  34962. /** @hidden */
  34963. Material.prototype._preBind = function (effect, overrideOrientation) {
  34964. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34965. var engine = this._scene.getEngine();
  34966. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34967. var reverse = orientation === Material.ClockWiseSideOrientation;
  34968. engine.enableEffect(effect ? effect : this._effect);
  34969. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34970. return reverse;
  34971. };
  34972. /**
  34973. * Binds the material to the mesh
  34974. * @param world defines the world transformation matrix
  34975. * @param mesh defines the mesh to bind the material to
  34976. */
  34977. Material.prototype.bind = function (world, mesh) {
  34978. };
  34979. /**
  34980. * Binds the submesh to the material
  34981. * @param world defines the world transformation matrix
  34982. * @param mesh defines the mesh containing the submesh
  34983. * @param subMesh defines the submesh to bind the material to
  34984. */
  34985. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34986. };
  34987. /**
  34988. * Binds the world matrix to the material
  34989. * @param world defines the world transformation matrix
  34990. */
  34991. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34992. };
  34993. /**
  34994. * Binds the scene's uniform buffer to the effect.
  34995. * @param effect defines the effect to bind to the scene uniform buffer
  34996. * @param sceneUbo defines the uniform buffer storing scene data
  34997. */
  34998. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34999. sceneUbo.bindToEffect(effect, "Scene");
  35000. };
  35001. /**
  35002. * Binds the view matrix to the effect
  35003. * @param effect defines the effect to bind the view matrix to
  35004. */
  35005. Material.prototype.bindView = function (effect) {
  35006. if (!this._useUBO) {
  35007. effect.setMatrix("view", this.getScene().getViewMatrix());
  35008. }
  35009. else {
  35010. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35011. }
  35012. };
  35013. /**
  35014. * Binds the view projection matrix to the effect
  35015. * @param effect defines the effect to bind the view projection matrix to
  35016. */
  35017. Material.prototype.bindViewProjection = function (effect) {
  35018. if (!this._useUBO) {
  35019. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35020. }
  35021. else {
  35022. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35023. }
  35024. };
  35025. /**
  35026. * Specifies if material alpha testing should be turned on for the mesh
  35027. * @param mesh defines the mesh to check
  35028. */
  35029. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35030. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35031. };
  35032. /**
  35033. * Processes to execute after binding the material to a mesh
  35034. * @param mesh defines the rendered mesh
  35035. */
  35036. Material.prototype._afterBind = function (mesh) {
  35037. this._scene._cachedMaterial = this;
  35038. if (mesh) {
  35039. this._scene._cachedVisibility = mesh.visibility;
  35040. }
  35041. else {
  35042. this._scene._cachedVisibility = 1;
  35043. }
  35044. if (mesh) {
  35045. this.onBindObservable.notifyObservers(mesh);
  35046. }
  35047. if (this.disableDepthWrite) {
  35048. var engine = this._scene.getEngine();
  35049. this._cachedDepthWriteState = engine.getDepthWrite();
  35050. engine.setDepthWrite(false);
  35051. }
  35052. };
  35053. /**
  35054. * Unbinds the material from the mesh
  35055. */
  35056. Material.prototype.unbind = function () {
  35057. this.onUnBindObservable.notifyObservers(this);
  35058. if (this.disableDepthWrite) {
  35059. var engine = this._scene.getEngine();
  35060. engine.setDepthWrite(this._cachedDepthWriteState);
  35061. }
  35062. };
  35063. /**
  35064. * Gets the active textures from the material
  35065. * @returns an array of textures
  35066. */
  35067. Material.prototype.getActiveTextures = function () {
  35068. return [];
  35069. };
  35070. /**
  35071. * Specifies if the material uses a texture
  35072. * @param texture defines the texture to check against the material
  35073. * @returns a boolean specifying if the material uses the texture
  35074. */
  35075. Material.prototype.hasTexture = function (texture) {
  35076. return false;
  35077. };
  35078. /**
  35079. * Makes a duplicate of the material, and gives it a new name
  35080. * @param name defines the new name for the duplicated material
  35081. * @returns the cloned material
  35082. */
  35083. Material.prototype.clone = function (name) {
  35084. return null;
  35085. };
  35086. /**
  35087. * Gets the meshes bound to the material
  35088. * @returns an array of meshes bound to the material
  35089. */
  35090. Material.prototype.getBindedMeshes = function () {
  35091. var result = new Array();
  35092. for (var index = 0; index < this._scene.meshes.length; index++) {
  35093. var mesh = this._scene.meshes[index];
  35094. if (mesh.material === this) {
  35095. result.push(mesh);
  35096. }
  35097. }
  35098. return result;
  35099. };
  35100. /**
  35101. * Force shader compilation
  35102. * @param mesh defines the mesh associated with this material
  35103. * @param onCompiled defines a function to execute once the material is compiled
  35104. * @param options defines the options to configure the compilation
  35105. */
  35106. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35107. var _this = this;
  35108. var localOptions = __assign({ clipPlane: false }, options);
  35109. var subMesh = new BABYLON.BaseSubMesh();
  35110. var scene = this.getScene();
  35111. var checkReady = function () {
  35112. if (!_this._scene || !_this._scene.getEngine()) {
  35113. return;
  35114. }
  35115. if (subMesh._materialDefines) {
  35116. subMesh._materialDefines._renderId = -1;
  35117. }
  35118. var clipPlaneState = scene.clipPlane;
  35119. if (localOptions.clipPlane) {
  35120. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35121. }
  35122. if (_this.storeEffectOnSubMeshes) {
  35123. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35124. if (onCompiled) {
  35125. onCompiled(_this);
  35126. }
  35127. }
  35128. else {
  35129. setTimeout(checkReady, 16);
  35130. }
  35131. }
  35132. else {
  35133. if (_this.isReady(mesh)) {
  35134. if (onCompiled) {
  35135. onCompiled(_this);
  35136. }
  35137. }
  35138. else {
  35139. setTimeout(checkReady, 16);
  35140. }
  35141. }
  35142. if (localOptions.clipPlane) {
  35143. scene.clipPlane = clipPlaneState;
  35144. }
  35145. };
  35146. checkReady();
  35147. };
  35148. /**
  35149. * Force shader compilation
  35150. * @param mesh defines the mesh that will use this material
  35151. * @param options defines additional options for compiling the shaders
  35152. * @returns a promise that resolves when the compilation completes
  35153. */
  35154. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35155. var _this = this;
  35156. return new Promise(function (resolve) {
  35157. _this.forceCompilation(mesh, function () {
  35158. resolve();
  35159. }, options);
  35160. });
  35161. };
  35162. /**
  35163. * Marks a define in the material to indicate that it needs to be re-computed
  35164. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35165. */
  35166. Material.prototype.markAsDirty = function (flag) {
  35167. if (flag & Material.TextureDirtyFlag) {
  35168. this._markAllSubMeshesAsTexturesDirty();
  35169. }
  35170. if (flag & Material.LightDirtyFlag) {
  35171. this._markAllSubMeshesAsLightsDirty();
  35172. }
  35173. if (flag & Material.FresnelDirtyFlag) {
  35174. this._markAllSubMeshesAsFresnelDirty();
  35175. }
  35176. if (flag & Material.AttributesDirtyFlag) {
  35177. this._markAllSubMeshesAsAttributesDirty();
  35178. }
  35179. if (flag & Material.MiscDirtyFlag) {
  35180. this._markAllSubMeshesAsMiscDirty();
  35181. }
  35182. this.getScene().resetCachedMaterial();
  35183. };
  35184. /**
  35185. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35186. * @param func defines a function which checks material defines against the submeshes
  35187. */
  35188. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35189. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35190. var mesh = _a[_i];
  35191. if (!mesh.subMeshes) {
  35192. continue;
  35193. }
  35194. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35195. var subMesh = _c[_b];
  35196. if (subMesh.getMaterial() !== this) {
  35197. continue;
  35198. }
  35199. if (!subMesh._materialDefines) {
  35200. continue;
  35201. }
  35202. func(subMesh._materialDefines);
  35203. }
  35204. }
  35205. };
  35206. /**
  35207. * Indicates that image processing needs to be re-calculated for all submeshes
  35208. */
  35209. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35210. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35211. };
  35212. /**
  35213. * Indicates that textures need to be re-calculated for all submeshes
  35214. */
  35215. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35216. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35217. };
  35218. /**
  35219. * Indicates that fresnel needs to be re-calculated for all submeshes
  35220. */
  35221. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35222. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35223. };
  35224. /**
  35225. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35226. */
  35227. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35228. this._markAllSubMeshesAsDirty(function (defines) {
  35229. defines.markAsFresnelDirty();
  35230. defines.markAsMiscDirty();
  35231. });
  35232. };
  35233. /**
  35234. * Indicates that lights need to be re-calculated for all submeshes
  35235. */
  35236. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35237. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35238. };
  35239. /**
  35240. * Indicates that attributes need to be re-calculated for all submeshes
  35241. */
  35242. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35243. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35244. };
  35245. /**
  35246. * Indicates that misc needs to be re-calculated for all submeshes
  35247. */
  35248. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35249. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35250. };
  35251. /**
  35252. * Indicates that textures and misc need to be re-calculated for all submeshes
  35253. */
  35254. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35255. this._markAllSubMeshesAsDirty(function (defines) {
  35256. defines.markAsTexturesDirty();
  35257. defines.markAsMiscDirty();
  35258. });
  35259. };
  35260. /**
  35261. * Disposes the material
  35262. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35263. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35264. */
  35265. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35266. // Animations
  35267. this.getScene().stopAnimation(this);
  35268. this.getScene().freeProcessedMaterials();
  35269. // Remove from scene
  35270. var index = this._scene.materials.indexOf(this);
  35271. if (index >= 0) {
  35272. this._scene.materials.splice(index, 1);
  35273. }
  35274. // Remove from meshes
  35275. for (index = 0; index < this._scene.meshes.length; index++) {
  35276. var mesh = this._scene.meshes[index];
  35277. if (mesh.material === this) {
  35278. mesh.material = null;
  35279. if (mesh.geometry) {
  35280. var geometry = (mesh.geometry);
  35281. if (this.storeEffectOnSubMeshes) {
  35282. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35283. var subMesh = _a[_i];
  35284. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35285. if (forceDisposeEffect && subMesh._materialEffect) {
  35286. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35287. }
  35288. }
  35289. }
  35290. else {
  35291. geometry._releaseVertexArrayObject(this._effect);
  35292. }
  35293. }
  35294. }
  35295. }
  35296. this._uniformBuffer.dispose();
  35297. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35298. if (forceDisposeEffect && this._effect) {
  35299. if (!this.storeEffectOnSubMeshes) {
  35300. this._scene.getEngine()._releaseEffect(this._effect);
  35301. }
  35302. this._effect = null;
  35303. }
  35304. // Callback
  35305. this.onDisposeObservable.notifyObservers(this);
  35306. this.onDisposeObservable.clear();
  35307. this.onBindObservable.clear();
  35308. this.onUnBindObservable.clear();
  35309. };
  35310. /**
  35311. * Serializes this material
  35312. * @returns the serialized material object
  35313. */
  35314. Material.prototype.serialize = function () {
  35315. return BABYLON.SerializationHelper.Serialize(this);
  35316. };
  35317. /**
  35318. * Creates a MultiMaterial from parsed MultiMaterial data.
  35319. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35320. * @param scene defines the hosting scene
  35321. * @returns a new MultiMaterial
  35322. */
  35323. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35324. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35325. multiMaterial.id = parsedMultiMaterial.id;
  35326. if (BABYLON.Tags) {
  35327. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35328. }
  35329. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35330. var subMatId = parsedMultiMaterial.materials[matIndex];
  35331. if (subMatId) {
  35332. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35333. }
  35334. else {
  35335. multiMaterial.subMaterials.push(null);
  35336. }
  35337. }
  35338. return multiMaterial;
  35339. };
  35340. /**
  35341. * Creates a material from parsed material data
  35342. * @param parsedMaterial defines parsed material data
  35343. * @param scene defines the hosting scene
  35344. * @param rootUrl defines the root URL to use to load textures
  35345. * @returns a new material
  35346. */
  35347. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35348. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35349. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35350. }
  35351. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35352. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35353. if (!BABYLON.LegacyPBRMaterial) {
  35354. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35355. return;
  35356. }
  35357. }
  35358. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35359. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35360. };
  35361. // Triangle views
  35362. Material._TriangleFillMode = 0;
  35363. Material._WireFrameFillMode = 1;
  35364. Material._PointFillMode = 2;
  35365. // Draw modes
  35366. Material._PointListDrawMode = 3;
  35367. Material._LineListDrawMode = 4;
  35368. Material._LineLoopDrawMode = 5;
  35369. Material._LineStripDrawMode = 6;
  35370. Material._TriangleStripDrawMode = 7;
  35371. Material._TriangleFanDrawMode = 8;
  35372. /**
  35373. * Stores the clock-wise side orientation
  35374. */
  35375. Material._ClockWiseSideOrientation = 0;
  35376. /**
  35377. * Stores the counter clock-wise side orientation
  35378. */
  35379. Material._CounterClockWiseSideOrientation = 1;
  35380. /**
  35381. * The dirty texture flag value
  35382. */
  35383. Material._TextureDirtyFlag = 1;
  35384. /**
  35385. * The dirty light flag value
  35386. */
  35387. Material._LightDirtyFlag = 2;
  35388. /**
  35389. * The dirty fresnel flag value
  35390. */
  35391. Material._FresnelDirtyFlag = 4;
  35392. /**
  35393. * The dirty attribute flag value
  35394. */
  35395. Material._AttributesDirtyFlag = 8;
  35396. /**
  35397. * The dirty misc flag value
  35398. */
  35399. Material._MiscDirtyFlag = 16;
  35400. __decorate([
  35401. BABYLON.serialize()
  35402. ], Material.prototype, "id", void 0);
  35403. __decorate([
  35404. BABYLON.serialize()
  35405. ], Material.prototype, "name", void 0);
  35406. __decorate([
  35407. BABYLON.serialize()
  35408. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35409. __decorate([
  35410. BABYLON.serialize()
  35411. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35412. __decorate([
  35413. BABYLON.serialize()
  35414. ], Material.prototype, "state", void 0);
  35415. __decorate([
  35416. BABYLON.serialize("alpha")
  35417. ], Material.prototype, "_alpha", void 0);
  35418. __decorate([
  35419. BABYLON.serialize("backFaceCulling")
  35420. ], Material.prototype, "_backFaceCulling", void 0);
  35421. __decorate([
  35422. BABYLON.serialize()
  35423. ], Material.prototype, "sideOrientation", void 0);
  35424. __decorate([
  35425. BABYLON.serialize("alphaMode")
  35426. ], Material.prototype, "_alphaMode", void 0);
  35427. __decorate([
  35428. BABYLON.serialize()
  35429. ], Material.prototype, "_needDepthPrePass", void 0);
  35430. __decorate([
  35431. BABYLON.serialize()
  35432. ], Material.prototype, "disableDepthWrite", void 0);
  35433. __decorate([
  35434. BABYLON.serialize()
  35435. ], Material.prototype, "forceDepthWrite", void 0);
  35436. __decorate([
  35437. BABYLON.serialize()
  35438. ], Material.prototype, "separateCullingPass", void 0);
  35439. __decorate([
  35440. BABYLON.serialize("fogEnabled")
  35441. ], Material.prototype, "_fogEnabled", void 0);
  35442. __decorate([
  35443. BABYLON.serialize()
  35444. ], Material.prototype, "pointSize", void 0);
  35445. __decorate([
  35446. BABYLON.serialize()
  35447. ], Material.prototype, "zOffset", void 0);
  35448. __decorate([
  35449. BABYLON.serialize()
  35450. ], Material.prototype, "wireframe", null);
  35451. __decorate([
  35452. BABYLON.serialize()
  35453. ], Material.prototype, "pointsCloud", null);
  35454. __decorate([
  35455. BABYLON.serialize()
  35456. ], Material.prototype, "fillMode", null);
  35457. return Material;
  35458. }());
  35459. BABYLON.Material = Material;
  35460. })(BABYLON || (BABYLON = {}));
  35461. //# sourceMappingURL=babylon.material.js.map
  35462. var BABYLON;
  35463. (function (BABYLON) {
  35464. var UniformBuffer = /** @class */ (function () {
  35465. /**
  35466. * Uniform buffer objects.
  35467. *
  35468. * Handles blocks of uniform on the GPU.
  35469. *
  35470. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35471. *
  35472. * For more information, please refer to :
  35473. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35474. */
  35475. function UniformBuffer(engine, data, dynamic) {
  35476. this._engine = engine;
  35477. this._noUBO = !engine.supportsUniformBuffers;
  35478. this._dynamic = dynamic;
  35479. this._data = data || [];
  35480. this._uniformLocations = {};
  35481. this._uniformSizes = {};
  35482. this._uniformLocationPointer = 0;
  35483. this._needSync = false;
  35484. if (this._noUBO) {
  35485. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35486. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35487. this.updateFloat = this._updateFloatForEffect;
  35488. this.updateFloat2 = this._updateFloat2ForEffect;
  35489. this.updateFloat3 = this._updateFloat3ForEffect;
  35490. this.updateFloat4 = this._updateFloat4ForEffect;
  35491. this.updateMatrix = this._updateMatrixForEffect;
  35492. this.updateVector3 = this._updateVector3ForEffect;
  35493. this.updateVector4 = this._updateVector4ForEffect;
  35494. this.updateColor3 = this._updateColor3ForEffect;
  35495. this.updateColor4 = this._updateColor4ForEffect;
  35496. }
  35497. else {
  35498. this._engine._uniformBuffers.push(this);
  35499. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35500. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35501. this.updateFloat = this._updateFloatForUniform;
  35502. this.updateFloat2 = this._updateFloat2ForUniform;
  35503. this.updateFloat3 = this._updateFloat3ForUniform;
  35504. this.updateFloat4 = this._updateFloat4ForUniform;
  35505. this.updateMatrix = this._updateMatrixForUniform;
  35506. this.updateVector3 = this._updateVector3ForUniform;
  35507. this.updateVector4 = this._updateVector4ForUniform;
  35508. this.updateColor3 = this._updateColor3ForUniform;
  35509. this.updateColor4 = this._updateColor4ForUniform;
  35510. }
  35511. }
  35512. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35513. // Properties
  35514. /**
  35515. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35516. * or just falling back on setUniformXXX calls.
  35517. */
  35518. get: function () {
  35519. return !this._noUBO;
  35520. },
  35521. enumerable: true,
  35522. configurable: true
  35523. });
  35524. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35525. /**
  35526. * Indicates if the WebGL underlying uniform buffer is in sync
  35527. * with the javascript cache data.
  35528. */
  35529. get: function () {
  35530. return !this._needSync;
  35531. },
  35532. enumerable: true,
  35533. configurable: true
  35534. });
  35535. /**
  35536. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35537. * Also, a dynamic UniformBuffer will disable cache verification and always
  35538. * update the underlying WebGL uniform buffer to the GPU.
  35539. */
  35540. UniformBuffer.prototype.isDynamic = function () {
  35541. return this._dynamic !== undefined;
  35542. };
  35543. /**
  35544. * The data cache on JS side.
  35545. */
  35546. UniformBuffer.prototype.getData = function () {
  35547. return this._bufferData;
  35548. };
  35549. /**
  35550. * The underlying WebGL Uniform buffer.
  35551. */
  35552. UniformBuffer.prototype.getBuffer = function () {
  35553. return this._buffer;
  35554. };
  35555. /**
  35556. * std140 layout specifies how to align data within an UBO structure.
  35557. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35558. * for specs.
  35559. */
  35560. UniformBuffer.prototype._fillAlignment = function (size) {
  35561. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35562. // and 4x4 matrices
  35563. // TODO : change if other types are used
  35564. var alignment;
  35565. if (size <= 2) {
  35566. alignment = size;
  35567. }
  35568. else {
  35569. alignment = 4;
  35570. }
  35571. if ((this._uniformLocationPointer % alignment) !== 0) {
  35572. var oldPointer = this._uniformLocationPointer;
  35573. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35574. var diff = this._uniformLocationPointer - oldPointer;
  35575. for (var i = 0; i < diff; i++) {
  35576. this._data.push(0);
  35577. }
  35578. }
  35579. };
  35580. /**
  35581. * Adds an uniform in the buffer.
  35582. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35583. * for the layout to be correct !
  35584. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35585. * @param {number|number[]} size Data size, or data directly.
  35586. */
  35587. UniformBuffer.prototype.addUniform = function (name, size) {
  35588. if (this._noUBO) {
  35589. return;
  35590. }
  35591. if (this._uniformLocations[name] !== undefined) {
  35592. // Already existing uniform
  35593. return;
  35594. }
  35595. // This function must be called in the order of the shader layout !
  35596. // size can be the size of the uniform, or data directly
  35597. var data;
  35598. if (size instanceof Array) {
  35599. data = size;
  35600. size = data.length;
  35601. }
  35602. else {
  35603. size = size;
  35604. data = [];
  35605. // Fill with zeros
  35606. for (var i = 0; i < size; i++) {
  35607. data.push(0);
  35608. }
  35609. }
  35610. this._fillAlignment(size);
  35611. this._uniformSizes[name] = size;
  35612. this._uniformLocations[name] = this._uniformLocationPointer;
  35613. this._uniformLocationPointer += size;
  35614. for (var i = 0; i < size; i++) {
  35615. this._data.push(data[i]);
  35616. }
  35617. this._needSync = true;
  35618. };
  35619. /**
  35620. * Wrapper for addUniform.
  35621. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35622. * @param {Matrix} mat A 4x4 matrix.
  35623. */
  35624. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35625. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35626. };
  35627. /**
  35628. * Wrapper for addUniform.
  35629. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35630. * @param {number} x
  35631. * @param {number} y
  35632. */
  35633. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35634. var temp = [x, y];
  35635. this.addUniform(name, temp);
  35636. };
  35637. /**
  35638. * Wrapper for addUniform.
  35639. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35640. * @param {number} x
  35641. * @param {number} y
  35642. * @param {number} z
  35643. */
  35644. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35645. var temp = [x, y, z];
  35646. this.addUniform(name, temp);
  35647. };
  35648. /**
  35649. * Wrapper for addUniform.
  35650. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35651. * @param {Color3} color
  35652. */
  35653. UniformBuffer.prototype.addColor3 = function (name, color) {
  35654. var temp = new Array();
  35655. color.toArray(temp);
  35656. this.addUniform(name, temp);
  35657. };
  35658. /**
  35659. * Wrapper for addUniform.
  35660. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35661. * @param {Color3} color
  35662. * @param {number} alpha
  35663. */
  35664. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35665. var temp = new Array();
  35666. color.toArray(temp);
  35667. temp.push(alpha);
  35668. this.addUniform(name, temp);
  35669. };
  35670. /**
  35671. * Wrapper for addUniform.
  35672. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35673. * @param {Vector3} vector
  35674. */
  35675. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35676. var temp = new Array();
  35677. vector.toArray(temp);
  35678. this.addUniform(name, temp);
  35679. };
  35680. /**
  35681. * Wrapper for addUniform.
  35682. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35683. */
  35684. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35685. this.addUniform(name, 12);
  35686. };
  35687. /**
  35688. * Wrapper for addUniform.
  35689. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35690. */
  35691. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35692. this.addUniform(name, 8);
  35693. };
  35694. /**
  35695. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35696. */
  35697. UniformBuffer.prototype.create = function () {
  35698. if (this._noUBO) {
  35699. return;
  35700. }
  35701. if (this._buffer) {
  35702. return; // nothing to do
  35703. }
  35704. // See spec, alignment must be filled as a vec4
  35705. this._fillAlignment(4);
  35706. this._bufferData = new Float32Array(this._data);
  35707. this._rebuild();
  35708. this._needSync = true;
  35709. };
  35710. UniformBuffer.prototype._rebuild = function () {
  35711. if (this._noUBO) {
  35712. return;
  35713. }
  35714. if (this._dynamic) {
  35715. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35716. }
  35717. else {
  35718. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35719. }
  35720. };
  35721. /**
  35722. * Updates the WebGL Uniform Buffer on the GPU.
  35723. * If the `dynamic` flag is set to true, no cache comparison is done.
  35724. * Otherwise, the buffer will be updated only if the cache differs.
  35725. */
  35726. UniformBuffer.prototype.update = function () {
  35727. if (!this._buffer) {
  35728. this.create();
  35729. return;
  35730. }
  35731. if (!this._dynamic && !this._needSync) {
  35732. return;
  35733. }
  35734. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35735. this._needSync = false;
  35736. };
  35737. /**
  35738. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35739. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35740. * @param {number[]|Float32Array} data Flattened data
  35741. * @param {number} size Size of the data.
  35742. */
  35743. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35744. var location = this._uniformLocations[uniformName];
  35745. if (location === undefined) {
  35746. if (this._buffer) {
  35747. // Cannot add an uniform if the buffer is already created
  35748. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35749. return;
  35750. }
  35751. this.addUniform(uniformName, size);
  35752. location = this._uniformLocations[uniformName];
  35753. }
  35754. if (!this._buffer) {
  35755. this.create();
  35756. }
  35757. if (!this._dynamic) {
  35758. // Cache for static uniform buffers
  35759. var changed = false;
  35760. for (var i = 0; i < size; i++) {
  35761. if (this._bufferData[location + i] !== data[i]) {
  35762. changed = true;
  35763. this._bufferData[location + i] = data[i];
  35764. }
  35765. }
  35766. this._needSync = this._needSync || changed;
  35767. }
  35768. else {
  35769. // No cache for dynamic
  35770. for (var i = 0; i < size; i++) {
  35771. this._bufferData[location + i] = data[i];
  35772. }
  35773. }
  35774. };
  35775. // Update methods
  35776. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35777. // To match std140, matrix must be realigned
  35778. for (var i = 0; i < 3; i++) {
  35779. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35780. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35781. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35782. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35783. }
  35784. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35785. };
  35786. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35787. this._currentEffect.setMatrix3x3(name, matrix);
  35788. };
  35789. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35790. this._currentEffect.setMatrix2x2(name, matrix);
  35791. };
  35792. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35793. // To match std140, matrix must be realigned
  35794. for (var i = 0; i < 2; i++) {
  35795. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35796. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35797. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35798. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35799. }
  35800. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35801. };
  35802. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35803. this._currentEffect.setFloat(name, x);
  35804. };
  35805. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35806. UniformBuffer._tempBuffer[0] = x;
  35807. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35808. };
  35809. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35810. if (suffix === void 0) { suffix = ""; }
  35811. this._currentEffect.setFloat2(name + suffix, x, y);
  35812. };
  35813. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35814. if (suffix === void 0) { suffix = ""; }
  35815. UniformBuffer._tempBuffer[0] = x;
  35816. UniformBuffer._tempBuffer[1] = y;
  35817. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35818. };
  35819. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35820. if (suffix === void 0) { suffix = ""; }
  35821. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35822. };
  35823. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35824. if (suffix === void 0) { suffix = ""; }
  35825. UniformBuffer._tempBuffer[0] = x;
  35826. UniformBuffer._tempBuffer[1] = y;
  35827. UniformBuffer._tempBuffer[2] = z;
  35828. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35829. };
  35830. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35831. if (suffix === void 0) { suffix = ""; }
  35832. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35833. };
  35834. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35835. if (suffix === void 0) { suffix = ""; }
  35836. UniformBuffer._tempBuffer[0] = x;
  35837. UniformBuffer._tempBuffer[1] = y;
  35838. UniformBuffer._tempBuffer[2] = z;
  35839. UniformBuffer._tempBuffer[3] = w;
  35840. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35841. };
  35842. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35843. this._currentEffect.setMatrix(name, mat);
  35844. };
  35845. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35846. this.updateUniform(name, mat.toArray(), 16);
  35847. };
  35848. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35849. this._currentEffect.setVector3(name, vector);
  35850. };
  35851. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35852. vector.toArray(UniformBuffer._tempBuffer);
  35853. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35854. };
  35855. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35856. this._currentEffect.setVector4(name, vector);
  35857. };
  35858. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35859. vector.toArray(UniformBuffer._tempBuffer);
  35860. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35861. };
  35862. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35863. if (suffix === void 0) { suffix = ""; }
  35864. this._currentEffect.setColor3(name + suffix, color);
  35865. };
  35866. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35867. if (suffix === void 0) { suffix = ""; }
  35868. color.toArray(UniformBuffer._tempBuffer);
  35869. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35870. };
  35871. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35872. if (suffix === void 0) { suffix = ""; }
  35873. this._currentEffect.setColor4(name + suffix, color, alpha);
  35874. };
  35875. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35876. if (suffix === void 0) { suffix = ""; }
  35877. color.toArray(UniformBuffer._tempBuffer);
  35878. UniformBuffer._tempBuffer[3] = alpha;
  35879. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35880. };
  35881. /**
  35882. * Sets a sampler uniform on the effect.
  35883. * @param {string} name Name of the sampler.
  35884. * @param {Texture} texture
  35885. */
  35886. UniformBuffer.prototype.setTexture = function (name, texture) {
  35887. this._currentEffect.setTexture(name, texture);
  35888. };
  35889. /**
  35890. * Directly updates the value of the uniform in the cache AND on the GPU.
  35891. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35892. * @param {number[]|Float32Array} data Flattened data
  35893. */
  35894. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35895. this.updateUniform(uniformName, data, data.length);
  35896. this.update();
  35897. };
  35898. /**
  35899. * Binds this uniform buffer to an effect.
  35900. * @param {Effect} effect
  35901. * @param {string} name Name of the uniform block in the shader.
  35902. */
  35903. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35904. this._currentEffect = effect;
  35905. if (this._noUBO || !this._buffer) {
  35906. return;
  35907. }
  35908. effect.bindUniformBuffer(this._buffer, name);
  35909. };
  35910. /**
  35911. * Disposes the uniform buffer.
  35912. */
  35913. UniformBuffer.prototype.dispose = function () {
  35914. if (this._noUBO) {
  35915. return;
  35916. }
  35917. var index = this._engine._uniformBuffers.indexOf(this);
  35918. if (index !== -1) {
  35919. this._engine._uniformBuffers.splice(index, 1);
  35920. }
  35921. if (!this._buffer) {
  35922. return;
  35923. }
  35924. if (this._engine._releaseBuffer(this._buffer)) {
  35925. this._buffer = null;
  35926. }
  35927. };
  35928. // Pool for avoiding memory leaks
  35929. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35930. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35931. return UniformBuffer;
  35932. }());
  35933. BABYLON.UniformBuffer = UniformBuffer;
  35934. })(BABYLON || (BABYLON = {}));
  35935. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35936. var BABYLON;
  35937. (function (BABYLON) {
  35938. /**
  35939. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35940. */
  35941. var VertexData = /** @class */ (function () {
  35942. function VertexData() {
  35943. }
  35944. /**
  35945. * Uses the passed data array to set the set the values for the specified kind of data
  35946. * @param data a linear array of floating numbers
  35947. * @param kind the type of data that is being set, eg positions, colors etc
  35948. */
  35949. VertexData.prototype.set = function (data, kind) {
  35950. switch (kind) {
  35951. case BABYLON.VertexBuffer.PositionKind:
  35952. this.positions = data;
  35953. break;
  35954. case BABYLON.VertexBuffer.NormalKind:
  35955. this.normals = data;
  35956. break;
  35957. case BABYLON.VertexBuffer.TangentKind:
  35958. this.tangents = data;
  35959. break;
  35960. case BABYLON.VertexBuffer.UVKind:
  35961. this.uvs = data;
  35962. break;
  35963. case BABYLON.VertexBuffer.UV2Kind:
  35964. this.uvs2 = data;
  35965. break;
  35966. case BABYLON.VertexBuffer.UV3Kind:
  35967. this.uvs3 = data;
  35968. break;
  35969. case BABYLON.VertexBuffer.UV4Kind:
  35970. this.uvs4 = data;
  35971. break;
  35972. case BABYLON.VertexBuffer.UV5Kind:
  35973. this.uvs5 = data;
  35974. break;
  35975. case BABYLON.VertexBuffer.UV6Kind:
  35976. this.uvs6 = data;
  35977. break;
  35978. case BABYLON.VertexBuffer.ColorKind:
  35979. this.colors = data;
  35980. break;
  35981. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35982. this.matricesIndices = data;
  35983. break;
  35984. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35985. this.matricesWeights = data;
  35986. break;
  35987. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35988. this.matricesIndicesExtra = data;
  35989. break;
  35990. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35991. this.matricesWeightsExtra = data;
  35992. break;
  35993. }
  35994. };
  35995. /**
  35996. * Associates the vertexData to the passed Mesh.
  35997. * Sets it as updatable or not (default `false`)
  35998. * @param mesh the mesh the vertexData is applied to
  35999. * @param updatable when used and having the value true allows new data to update the vertexData
  36000. * @returns the VertexData
  36001. */
  36002. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36003. this._applyTo(mesh, updatable);
  36004. return this;
  36005. };
  36006. /**
  36007. * Associates the vertexData to the passed Geometry.
  36008. * Sets it as updatable or not (default `false`)
  36009. * @param geometry the geometry the vertexData is applied to
  36010. * @param updatable when used and having the value true allows new data to update the vertexData
  36011. * @returns VertexData
  36012. */
  36013. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36014. this._applyTo(geometry, updatable);
  36015. return this;
  36016. };
  36017. /**
  36018. * Updates the associated mesh
  36019. * @param mesh the mesh to be updated
  36020. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36021. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36022. * @returns VertexData
  36023. */
  36024. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36025. this._update(mesh);
  36026. return this;
  36027. };
  36028. /**
  36029. * Updates the associated geometry
  36030. * @param geometry the geometry to be updated
  36031. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36032. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36033. * @returns VertexData.
  36034. */
  36035. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36036. this._update(geometry);
  36037. return this;
  36038. };
  36039. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36040. if (updatable === void 0) { updatable = false; }
  36041. if (this.positions) {
  36042. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36043. }
  36044. if (this.normals) {
  36045. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36046. }
  36047. if (this.tangents) {
  36048. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36049. }
  36050. if (this.uvs) {
  36051. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36052. }
  36053. if (this.uvs2) {
  36054. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36055. }
  36056. if (this.uvs3) {
  36057. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36058. }
  36059. if (this.uvs4) {
  36060. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36061. }
  36062. if (this.uvs5) {
  36063. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36064. }
  36065. if (this.uvs6) {
  36066. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36067. }
  36068. if (this.colors) {
  36069. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36070. }
  36071. if (this.matricesIndices) {
  36072. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36073. }
  36074. if (this.matricesWeights) {
  36075. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36076. }
  36077. if (this.matricesIndicesExtra) {
  36078. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36079. }
  36080. if (this.matricesWeightsExtra) {
  36081. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36082. }
  36083. if (this.indices) {
  36084. meshOrGeometry.setIndices(this.indices, null, updatable);
  36085. }
  36086. return this;
  36087. };
  36088. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36089. if (this.positions) {
  36090. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36091. }
  36092. if (this.normals) {
  36093. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36094. }
  36095. if (this.tangents) {
  36096. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36097. }
  36098. if (this.uvs) {
  36099. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36100. }
  36101. if (this.uvs2) {
  36102. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36103. }
  36104. if (this.uvs3) {
  36105. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36106. }
  36107. if (this.uvs4) {
  36108. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36109. }
  36110. if (this.uvs5) {
  36111. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36112. }
  36113. if (this.uvs6) {
  36114. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36115. }
  36116. if (this.colors) {
  36117. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36118. }
  36119. if (this.matricesIndices) {
  36120. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36121. }
  36122. if (this.matricesWeights) {
  36123. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36124. }
  36125. if (this.matricesIndicesExtra) {
  36126. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36127. }
  36128. if (this.matricesWeightsExtra) {
  36129. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36130. }
  36131. if (this.indices) {
  36132. meshOrGeometry.setIndices(this.indices, null);
  36133. }
  36134. return this;
  36135. };
  36136. /**
  36137. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36138. * @param matrix the transforming matrix
  36139. * @returns the VertexData
  36140. */
  36141. VertexData.prototype.transform = function (matrix) {
  36142. var transformed = BABYLON.Vector3.Zero();
  36143. var index;
  36144. if (this.positions) {
  36145. var position = BABYLON.Vector3.Zero();
  36146. for (index = 0; index < this.positions.length; index += 3) {
  36147. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36148. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36149. this.positions[index] = transformed.x;
  36150. this.positions[index + 1] = transformed.y;
  36151. this.positions[index + 2] = transformed.z;
  36152. }
  36153. }
  36154. if (this.normals) {
  36155. var normal = BABYLON.Vector3.Zero();
  36156. for (index = 0; index < this.normals.length; index += 3) {
  36157. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36158. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36159. this.normals[index] = transformed.x;
  36160. this.normals[index + 1] = transformed.y;
  36161. this.normals[index + 2] = transformed.z;
  36162. }
  36163. }
  36164. if (this.tangents) {
  36165. var tangent = BABYLON.Vector4.Zero();
  36166. var tangentTransformed = BABYLON.Vector4.Zero();
  36167. for (index = 0; index < this.tangents.length; index += 4) {
  36168. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36169. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36170. this.tangents[index] = tangentTransformed.x;
  36171. this.tangents[index + 1] = tangentTransformed.y;
  36172. this.tangents[index + 2] = tangentTransformed.z;
  36173. this.tangents[index + 3] = tangentTransformed.w;
  36174. }
  36175. }
  36176. return this;
  36177. };
  36178. /**
  36179. * Merges the passed VertexData into the current one
  36180. * @param other the VertexData to be merged into the current one
  36181. * @returns the modified VertexData
  36182. */
  36183. VertexData.prototype.merge = function (other) {
  36184. this._validate();
  36185. other._validate();
  36186. if (!this.normals !== !other.normals ||
  36187. !this.tangents !== !other.tangents ||
  36188. !this.uvs !== !other.uvs ||
  36189. !this.uvs2 !== !other.uvs2 ||
  36190. !this.uvs3 !== !other.uvs3 ||
  36191. !this.uvs4 !== !other.uvs4 ||
  36192. !this.uvs5 !== !other.uvs5 ||
  36193. !this.uvs6 !== !other.uvs6 ||
  36194. !this.colors !== !other.colors ||
  36195. !this.matricesIndices !== !other.matricesIndices ||
  36196. !this.matricesWeights !== !other.matricesWeights ||
  36197. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36198. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36199. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36200. }
  36201. if (other.indices) {
  36202. if (!this.indices) {
  36203. this.indices = [];
  36204. }
  36205. var offset = this.positions ? this.positions.length / 3 : 0;
  36206. for (var index = 0; index < other.indices.length; index++) {
  36207. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36208. this.indices.push(other.indices[index] + offset);
  36209. }
  36210. }
  36211. this.positions = this._mergeElement(this.positions, other.positions);
  36212. this.normals = this._mergeElement(this.normals, other.normals);
  36213. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36214. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36215. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36216. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36217. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36218. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36219. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36220. this.colors = this._mergeElement(this.colors, other.colors);
  36221. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36222. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36223. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36224. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36225. return this;
  36226. };
  36227. VertexData.prototype._mergeElement = function (source, other) {
  36228. if (!source) {
  36229. return other;
  36230. }
  36231. if (!other) {
  36232. return source;
  36233. }
  36234. var len = other.length + source.length;
  36235. var isSrcTypedArray = source instanceof Float32Array;
  36236. var isOthTypedArray = other instanceof Float32Array;
  36237. // use non-loop method when the source is Float32Array
  36238. if (isSrcTypedArray) {
  36239. var ret32 = new Float32Array(len);
  36240. ret32.set(source);
  36241. ret32.set(other, source.length);
  36242. return ret32;
  36243. // source is number[], when other is also use concat
  36244. }
  36245. else if (!isOthTypedArray) {
  36246. return source.concat(other);
  36247. // source is a number[], but other is a Float32Array, loop required
  36248. }
  36249. else {
  36250. var ret = source.slice(0); // copy source to a separate array
  36251. for (var i = 0, len = other.length; i < len; i++) {
  36252. ret.push(other[i]);
  36253. }
  36254. return ret;
  36255. }
  36256. };
  36257. VertexData.prototype._validate = function () {
  36258. if (!this.positions) {
  36259. throw new Error("Positions are required");
  36260. }
  36261. var getElementCount = function (kind, values) {
  36262. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36263. if ((values.length % stride) !== 0) {
  36264. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36265. }
  36266. return values.length / stride;
  36267. };
  36268. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36269. var validateElementCount = function (kind, values) {
  36270. var elementCount = getElementCount(kind, values);
  36271. if (elementCount !== positionsElementCount) {
  36272. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36273. }
  36274. };
  36275. if (this.normals)
  36276. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36277. if (this.tangents)
  36278. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36279. if (this.uvs)
  36280. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36281. if (this.uvs2)
  36282. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36283. if (this.uvs3)
  36284. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36285. if (this.uvs4)
  36286. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36287. if (this.uvs5)
  36288. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36289. if (this.uvs6)
  36290. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36291. if (this.colors)
  36292. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36293. if (this.matricesIndices)
  36294. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36295. if (this.matricesWeights)
  36296. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36297. if (this.matricesIndicesExtra)
  36298. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36299. if (this.matricesWeightsExtra)
  36300. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36301. };
  36302. /**
  36303. * Serializes the VertexData
  36304. * @returns a serialized object
  36305. */
  36306. VertexData.prototype.serialize = function () {
  36307. var serializationObject = this.serialize();
  36308. if (this.positions) {
  36309. serializationObject.positions = this.positions;
  36310. }
  36311. if (this.normals) {
  36312. serializationObject.normals = this.normals;
  36313. }
  36314. if (this.tangents) {
  36315. serializationObject.tangents = this.tangents;
  36316. }
  36317. if (this.uvs) {
  36318. serializationObject.uvs = this.uvs;
  36319. }
  36320. if (this.uvs2) {
  36321. serializationObject.uvs2 = this.uvs2;
  36322. }
  36323. if (this.uvs3) {
  36324. serializationObject.uvs3 = this.uvs3;
  36325. }
  36326. if (this.uvs4) {
  36327. serializationObject.uvs4 = this.uvs4;
  36328. }
  36329. if (this.uvs5) {
  36330. serializationObject.uvs5 = this.uvs5;
  36331. }
  36332. if (this.uvs6) {
  36333. serializationObject.uvs6 = this.uvs6;
  36334. }
  36335. if (this.colors) {
  36336. serializationObject.colors = this.colors;
  36337. }
  36338. if (this.matricesIndices) {
  36339. serializationObject.matricesIndices = this.matricesIndices;
  36340. serializationObject.matricesIndices._isExpanded = true;
  36341. }
  36342. if (this.matricesWeights) {
  36343. serializationObject.matricesWeights = this.matricesWeights;
  36344. }
  36345. if (this.matricesIndicesExtra) {
  36346. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36347. serializationObject.matricesIndicesExtra._isExpanded = true;
  36348. }
  36349. if (this.matricesWeightsExtra) {
  36350. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36351. }
  36352. serializationObject.indices = this.indices;
  36353. return serializationObject;
  36354. };
  36355. // Statics
  36356. /**
  36357. * Extracts the vertexData from a mesh
  36358. * @param mesh the mesh from which to extract the VertexData
  36359. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36360. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36361. * @returns the object VertexData associated to the passed mesh
  36362. */
  36363. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36364. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36365. };
  36366. /**
  36367. * Extracts the vertexData from the geometry
  36368. * @param geometry the geometry from which to extract the VertexData
  36369. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36370. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36371. * @returns the object VertexData associated to the passed mesh
  36372. */
  36373. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36374. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36375. };
  36376. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36377. var result = new VertexData();
  36378. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36379. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36380. }
  36381. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36382. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36383. }
  36384. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36385. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36386. }
  36387. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36388. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36389. }
  36390. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36391. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36392. }
  36393. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36394. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36395. }
  36396. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36397. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36398. }
  36399. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36400. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36401. }
  36402. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36403. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36404. }
  36405. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36406. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36407. }
  36408. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36409. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36410. }
  36411. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36412. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36413. }
  36414. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36415. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36416. }
  36417. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36418. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36419. }
  36420. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36421. return result;
  36422. };
  36423. /**
  36424. * Creates the VertexData for a Ribbon
  36425. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36426. * * pathArray array of paths, each of which an array of successive Vector3
  36427. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36428. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36429. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36430. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36431. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36432. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36433. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36434. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36435. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36436. * @returns the VertexData of the ribbon
  36437. */
  36438. VertexData.CreateRibbon = function (options) {
  36439. var pathArray = options.pathArray;
  36440. var closeArray = options.closeArray || false;
  36441. var closePath = options.closePath || false;
  36442. var invertUV = options.invertUV || false;
  36443. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36444. var offset = options.offset || defaultOffset;
  36445. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36446. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36447. var customUV = options.uvs;
  36448. var customColors = options.colors;
  36449. var positions = [];
  36450. var indices = [];
  36451. var normals = [];
  36452. var uvs = [];
  36453. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36454. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36455. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36456. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36457. var minlg; // minimal length among all paths from pathArray
  36458. var lg = []; // array of path lengths : nb of vertex per path
  36459. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36460. var p; // path iterator
  36461. var i; // point iterator
  36462. var j; // point iterator
  36463. // if single path in pathArray
  36464. if (pathArray.length < 2) {
  36465. var ar1 = [];
  36466. var ar2 = [];
  36467. for (i = 0; i < pathArray[0].length - offset; i++) {
  36468. ar1.push(pathArray[0][i]);
  36469. ar2.push(pathArray[0][i + offset]);
  36470. }
  36471. pathArray = [ar1, ar2];
  36472. }
  36473. // positions and horizontal distances (u)
  36474. var idc = 0;
  36475. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36476. var path;
  36477. var l;
  36478. minlg = pathArray[0].length;
  36479. var vectlg;
  36480. var dist;
  36481. for (p = 0; p < pathArray.length; p++) {
  36482. uTotalDistance[p] = 0;
  36483. us[p] = [0];
  36484. path = pathArray[p];
  36485. l = path.length;
  36486. minlg = (minlg < l) ? minlg : l;
  36487. j = 0;
  36488. while (j < l) {
  36489. positions.push(path[j].x, path[j].y, path[j].z);
  36490. if (j > 0) {
  36491. vectlg = path[j].subtract(path[j - 1]).length();
  36492. dist = vectlg + uTotalDistance[p];
  36493. us[p].push(dist);
  36494. uTotalDistance[p] = dist;
  36495. }
  36496. j++;
  36497. }
  36498. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36499. j--;
  36500. positions.push(path[0].x, path[0].y, path[0].z);
  36501. vectlg = path[j].subtract(path[0]).length();
  36502. dist = vectlg + uTotalDistance[p];
  36503. us[p].push(dist);
  36504. uTotalDistance[p] = dist;
  36505. }
  36506. lg[p] = l + closePathCorr;
  36507. idx[p] = idc;
  36508. idc += (l + closePathCorr);
  36509. }
  36510. // vertical distances (v)
  36511. var path1;
  36512. var path2;
  36513. var vertex1 = null;
  36514. var vertex2 = null;
  36515. for (i = 0; i < minlg + closePathCorr; i++) {
  36516. vTotalDistance[i] = 0;
  36517. vs[i] = [0];
  36518. for (p = 0; p < pathArray.length - 1; p++) {
  36519. path1 = pathArray[p];
  36520. path2 = pathArray[p + 1];
  36521. if (i === minlg) { // closePath
  36522. vertex1 = path1[0];
  36523. vertex2 = path2[0];
  36524. }
  36525. else {
  36526. vertex1 = path1[i];
  36527. vertex2 = path2[i];
  36528. }
  36529. vectlg = vertex2.subtract(vertex1).length();
  36530. dist = vectlg + vTotalDistance[i];
  36531. vs[i].push(dist);
  36532. vTotalDistance[i] = dist;
  36533. }
  36534. if (closeArray && vertex2 && vertex1) {
  36535. path1 = pathArray[p];
  36536. path2 = pathArray[0];
  36537. if (i === minlg) { // closePath
  36538. vertex2 = path2[0];
  36539. }
  36540. vectlg = vertex2.subtract(vertex1).length();
  36541. dist = vectlg + vTotalDistance[i];
  36542. vTotalDistance[i] = dist;
  36543. }
  36544. }
  36545. // uvs
  36546. var u;
  36547. var v;
  36548. if (customUV) {
  36549. for (p = 0; p < customUV.length; p++) {
  36550. uvs.push(customUV[p].x, customUV[p].y);
  36551. }
  36552. }
  36553. else {
  36554. for (p = 0; p < pathArray.length; p++) {
  36555. for (i = 0; i < minlg + closePathCorr; i++) {
  36556. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36557. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36558. if (invertUV) {
  36559. uvs.push(v, u);
  36560. }
  36561. else {
  36562. uvs.push(u, v);
  36563. }
  36564. }
  36565. }
  36566. }
  36567. // indices
  36568. p = 0; // path index
  36569. var pi = 0; // positions array index
  36570. var l1 = lg[p] - 1; // path1 length
  36571. var l2 = lg[p + 1] - 1; // path2 length
  36572. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36573. var shft = idx[1] - idx[0]; // shift
  36574. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36575. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36576. // 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
  36577. indices.push(pi, pi + shft, pi + 1);
  36578. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36579. pi += 1;
  36580. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36581. p++;
  36582. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36583. shft = idx[0] - idx[p];
  36584. l1 = lg[p] - 1;
  36585. l2 = lg[0] - 1;
  36586. }
  36587. else {
  36588. shft = idx[p + 1] - idx[p];
  36589. l1 = lg[p] - 1;
  36590. l2 = lg[p + 1] - 1;
  36591. }
  36592. pi = idx[p];
  36593. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36594. }
  36595. }
  36596. // normals
  36597. VertexData.ComputeNormals(positions, indices, normals);
  36598. if (closePath) { // update both the first and last vertex normals to their average value
  36599. var indexFirst = 0;
  36600. var indexLast = 0;
  36601. for (p = 0; p < pathArray.length; p++) {
  36602. indexFirst = idx[p] * 3;
  36603. if (p + 1 < pathArray.length) {
  36604. indexLast = (idx[p + 1] - 1) * 3;
  36605. }
  36606. else {
  36607. indexLast = normals.length - 3;
  36608. }
  36609. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36610. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36611. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36612. normals[indexLast] = normals[indexFirst];
  36613. normals[indexLast + 1] = normals[indexFirst + 1];
  36614. normals[indexLast + 2] = normals[indexFirst + 2];
  36615. }
  36616. }
  36617. // sides
  36618. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36619. // Colors
  36620. var colors = null;
  36621. if (customColors) {
  36622. colors = new Float32Array(customColors.length * 4);
  36623. for (var c = 0; c < customColors.length; c++) {
  36624. colors[c * 4] = customColors[c].r;
  36625. colors[c * 4 + 1] = customColors[c].g;
  36626. colors[c * 4 + 2] = customColors[c].b;
  36627. colors[c * 4 + 3] = customColors[c].a;
  36628. }
  36629. }
  36630. // Result
  36631. var vertexData = new VertexData();
  36632. var positions32 = new Float32Array(positions);
  36633. var normals32 = new Float32Array(normals);
  36634. var uvs32 = new Float32Array(uvs);
  36635. vertexData.indices = indices;
  36636. vertexData.positions = positions32;
  36637. vertexData.normals = normals32;
  36638. vertexData.uvs = uvs32;
  36639. if (colors) {
  36640. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36641. }
  36642. if (closePath) {
  36643. vertexData._idx = idx;
  36644. }
  36645. return vertexData;
  36646. };
  36647. /**
  36648. * Creates the VertexData for a box
  36649. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36650. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36651. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36652. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36653. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36654. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36655. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36656. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36657. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36658. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36659. * @returns the VertexData of the box
  36660. */
  36661. VertexData.CreateBox = function (options) {
  36662. var normalsSource = [
  36663. new BABYLON.Vector3(0, 0, 1),
  36664. new BABYLON.Vector3(0, 0, -1),
  36665. new BABYLON.Vector3(1, 0, 0),
  36666. new BABYLON.Vector3(-1, 0, 0),
  36667. new BABYLON.Vector3(0, 1, 0),
  36668. new BABYLON.Vector3(0, -1, 0)
  36669. ];
  36670. var indices = [];
  36671. var positions = [];
  36672. var normals = [];
  36673. var uvs = [];
  36674. var width = options.width || options.size || 1;
  36675. var height = options.height || options.size || 1;
  36676. var depth = options.depth || options.size || 1;
  36677. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36678. var faceUV = options.faceUV || new Array(6);
  36679. var faceColors = options.faceColors;
  36680. var colors = [];
  36681. // default face colors and UV if undefined
  36682. for (var f = 0; f < 6; f++) {
  36683. if (faceUV[f] === undefined) {
  36684. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36685. }
  36686. if (faceColors && faceColors[f] === undefined) {
  36687. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36688. }
  36689. }
  36690. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36691. // Create each face in turn.
  36692. for (var index = 0; index < normalsSource.length; index++) {
  36693. var normal = normalsSource[index];
  36694. // Get two vectors perpendicular to the face normal and to each other.
  36695. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36696. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36697. // Six indices (two triangles) per face.
  36698. var verticesLength = positions.length / 3;
  36699. indices.push(verticesLength);
  36700. indices.push(verticesLength + 1);
  36701. indices.push(verticesLength + 2);
  36702. indices.push(verticesLength);
  36703. indices.push(verticesLength + 2);
  36704. indices.push(verticesLength + 3);
  36705. // Four vertices per face.
  36706. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36707. positions.push(vertex.x, vertex.y, vertex.z);
  36708. normals.push(normal.x, normal.y, normal.z);
  36709. uvs.push(faceUV[index].z, faceUV[index].w);
  36710. if (faceColors) {
  36711. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36712. }
  36713. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36714. positions.push(vertex.x, vertex.y, vertex.z);
  36715. normals.push(normal.x, normal.y, normal.z);
  36716. uvs.push(faceUV[index].x, faceUV[index].w);
  36717. if (faceColors) {
  36718. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36719. }
  36720. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36721. positions.push(vertex.x, vertex.y, vertex.z);
  36722. normals.push(normal.x, normal.y, normal.z);
  36723. uvs.push(faceUV[index].x, faceUV[index].y);
  36724. if (faceColors) {
  36725. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36726. }
  36727. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36728. positions.push(vertex.x, vertex.y, vertex.z);
  36729. normals.push(normal.x, normal.y, normal.z);
  36730. uvs.push(faceUV[index].z, faceUV[index].y);
  36731. if (faceColors) {
  36732. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36733. }
  36734. }
  36735. // sides
  36736. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36737. // Result
  36738. var vertexData = new VertexData();
  36739. vertexData.indices = indices;
  36740. vertexData.positions = positions;
  36741. vertexData.normals = normals;
  36742. vertexData.uvs = uvs;
  36743. if (faceColors) {
  36744. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36745. vertexData.colors = totalColors;
  36746. }
  36747. return vertexData;
  36748. };
  36749. /**
  36750. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36751. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36752. * * segments sets the number of horizontal strips optional, default 32
  36753. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36754. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36755. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36756. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36757. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  36758. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  36759. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36760. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36761. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36762. * @returns the VertexData of the ellipsoid
  36763. */
  36764. VertexData.CreateSphere = function (options) {
  36765. var segments = options.segments || 32;
  36766. var diameterX = options.diameterX || options.diameter || 1;
  36767. var diameterY = options.diameterY || options.diameter || 1;
  36768. var diameterZ = options.diameterZ || options.diameter || 1;
  36769. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36770. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36771. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36772. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36773. var totalZRotationSteps = 2 + segments;
  36774. var totalYRotationSteps = 2 * totalZRotationSteps;
  36775. var indices = [];
  36776. var positions = [];
  36777. var normals = [];
  36778. var uvs = [];
  36779. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36780. var normalizedZ = zRotationStep / totalZRotationSteps;
  36781. var angleZ = normalizedZ * Math.PI * slice;
  36782. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36783. var normalizedY = yRotationStep / totalYRotationSteps;
  36784. var angleY = normalizedY * Math.PI * 2 * arc;
  36785. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36786. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36787. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36788. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36789. var vertex = complete.multiply(radius);
  36790. var normal = complete.divide(radius).normalize();
  36791. positions.push(vertex.x, vertex.y, vertex.z);
  36792. normals.push(normal.x, normal.y, normal.z);
  36793. uvs.push(normalizedY, normalizedZ);
  36794. }
  36795. if (zRotationStep > 0) {
  36796. var verticesCount = positions.length / 3;
  36797. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36798. indices.push((firstIndex));
  36799. indices.push((firstIndex + 1));
  36800. indices.push(firstIndex + totalYRotationSteps + 1);
  36801. indices.push((firstIndex + totalYRotationSteps + 1));
  36802. indices.push((firstIndex + 1));
  36803. indices.push((firstIndex + totalYRotationSteps + 2));
  36804. }
  36805. }
  36806. }
  36807. // Sides
  36808. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36809. // Result
  36810. var vertexData = new VertexData();
  36811. vertexData.indices = indices;
  36812. vertexData.positions = positions;
  36813. vertexData.normals = normals;
  36814. vertexData.uvs = uvs;
  36815. return vertexData;
  36816. };
  36817. /**
  36818. * Creates the VertexData for a cylinder, cone or prism
  36819. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36820. * * height sets the height (y direction) of the cylinder, optional, default 2
  36821. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36822. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36823. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36824. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36825. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36826. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  36827. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36828. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36829. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36830. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36831. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36832. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36833. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36834. * @returns the VertexData of the cylinder, cone or prism
  36835. */
  36836. VertexData.CreateCylinder = function (options) {
  36837. var height = options.height || 2;
  36838. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36839. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36840. var tessellation = options.tessellation || 24;
  36841. var subdivisions = options.subdivisions || 1;
  36842. var hasRings = options.hasRings ? true : false;
  36843. var enclose = options.enclose ? true : false;
  36844. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36845. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36846. var faceUV = options.faceUV || new Array(3);
  36847. var faceColors = options.faceColors;
  36848. // default face colors and UV if undefined
  36849. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36850. var ringNb = (hasRings) ? subdivisions : 1;
  36851. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36852. var f;
  36853. for (f = 0; f < surfaceNb; f++) {
  36854. if (faceColors && faceColors[f] === undefined) {
  36855. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36856. }
  36857. }
  36858. for (f = 0; f < surfaceNb; f++) {
  36859. if (faceUV && faceUV[f] === undefined) {
  36860. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36861. }
  36862. }
  36863. var indices = new Array();
  36864. var positions = new Array();
  36865. var normals = new Array();
  36866. var uvs = new Array();
  36867. var colors = new Array();
  36868. var angle_step = Math.PI * 2 * arc / tessellation;
  36869. var angle;
  36870. var h;
  36871. var radius;
  36872. var tan = (diameterBottom - diameterTop) / 2 / height;
  36873. var ringVertex = BABYLON.Vector3.Zero();
  36874. var ringNormal = BABYLON.Vector3.Zero();
  36875. var ringFirstVertex = BABYLON.Vector3.Zero();
  36876. var ringFirstNormal = BABYLON.Vector3.Zero();
  36877. var quadNormal = BABYLON.Vector3.Zero();
  36878. var Y = BABYLON.Axis.Y;
  36879. // positions, normals, uvs
  36880. var i;
  36881. var j;
  36882. var r;
  36883. var ringIdx = 1;
  36884. var s = 1; // surface index
  36885. var cs = 0;
  36886. var v = 0;
  36887. for (i = 0; i <= subdivisions; i++) {
  36888. h = i / subdivisions;
  36889. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36890. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36891. for (r = 0; r < ringIdx; r++) {
  36892. if (hasRings) {
  36893. s += r;
  36894. }
  36895. if (enclose) {
  36896. s += 2 * r;
  36897. }
  36898. for (j = 0; j <= tessellation; j++) {
  36899. angle = j * angle_step;
  36900. // position
  36901. ringVertex.x = Math.cos(-angle) * radius;
  36902. ringVertex.y = -height / 2 + h * height;
  36903. ringVertex.z = Math.sin(-angle) * radius;
  36904. // normal
  36905. if (diameterTop === 0 && i === subdivisions) {
  36906. // if no top cap, reuse former normals
  36907. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36908. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36909. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36910. }
  36911. else {
  36912. ringNormal.x = ringVertex.x;
  36913. ringNormal.z = ringVertex.z;
  36914. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36915. ringNormal.normalize();
  36916. }
  36917. // keep first ring vertex values for enclose
  36918. if (j === 0) {
  36919. ringFirstVertex.copyFrom(ringVertex);
  36920. ringFirstNormal.copyFrom(ringNormal);
  36921. }
  36922. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36923. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36924. if (hasRings) {
  36925. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36926. }
  36927. else {
  36928. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36929. }
  36930. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36931. if (faceColors) {
  36932. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36933. }
  36934. }
  36935. // if enclose, add four vertices and their dedicated normals
  36936. if (arc !== 1 && enclose) {
  36937. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36938. positions.push(0, ringVertex.y, 0);
  36939. positions.push(0, ringVertex.y, 0);
  36940. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36941. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36942. quadNormal.normalize();
  36943. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36944. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36945. quadNormal.normalize();
  36946. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36947. if (hasRings) {
  36948. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36949. }
  36950. else {
  36951. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36952. }
  36953. uvs.push(faceUV[s + 1].x, v);
  36954. uvs.push(faceUV[s + 1].z, v);
  36955. if (hasRings) {
  36956. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36957. }
  36958. else {
  36959. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36960. }
  36961. uvs.push(faceUV[s + 2].x, v);
  36962. uvs.push(faceUV[s + 2].z, v);
  36963. if (faceColors) {
  36964. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36965. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36966. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36967. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36968. }
  36969. }
  36970. if (cs !== s) {
  36971. cs = s;
  36972. }
  36973. }
  36974. }
  36975. // indices
  36976. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36977. var s;
  36978. i = 0;
  36979. for (s = 0; s < subdivisions; s++) {
  36980. var i0 = 0;
  36981. var i1 = 0;
  36982. var i2 = 0;
  36983. var i3 = 0;
  36984. for (j = 0; j < tessellation; j++) {
  36985. i0 = i * (e + 1) + j;
  36986. i1 = (i + 1) * (e + 1) + j;
  36987. i2 = i * (e + 1) + (j + 1);
  36988. i3 = (i + 1) * (e + 1) + (j + 1);
  36989. indices.push(i0, i1, i2);
  36990. indices.push(i3, i2, i1);
  36991. }
  36992. if (arc !== 1 && enclose) { // if enclose, add two quads
  36993. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36994. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36995. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36996. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36997. }
  36998. i = (hasRings) ? (i + 2) : (i + 1);
  36999. }
  37000. // Caps
  37001. var createCylinderCap = function (isTop) {
  37002. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37003. if (radius === 0) {
  37004. return;
  37005. }
  37006. // Cap positions, normals & uvs
  37007. var angle;
  37008. var circleVector;
  37009. var i;
  37010. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37011. var c = null;
  37012. if (faceColors) {
  37013. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37014. }
  37015. // cap center
  37016. var vbase = positions.length / 3;
  37017. var offset = isTop ? height / 2 : -height / 2;
  37018. var center = new BABYLON.Vector3(0, offset, 0);
  37019. positions.push(center.x, center.y, center.z);
  37020. normals.push(0, isTop ? 1 : -1, 0);
  37021. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37022. if (c) {
  37023. colors.push(c.r, c.g, c.b, c.a);
  37024. }
  37025. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37026. for (i = 0; i <= tessellation; i++) {
  37027. angle = Math.PI * 2 * i * arc / tessellation;
  37028. var cos = Math.cos(-angle);
  37029. var sin = Math.sin(-angle);
  37030. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37031. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37032. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37033. normals.push(0, isTop ? 1 : -1, 0);
  37034. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37035. if (c) {
  37036. colors.push(c.r, c.g, c.b, c.a);
  37037. }
  37038. }
  37039. // Cap indices
  37040. for (i = 0; i < tessellation; i++) {
  37041. if (!isTop) {
  37042. indices.push(vbase);
  37043. indices.push(vbase + (i + 1));
  37044. indices.push(vbase + (i + 2));
  37045. }
  37046. else {
  37047. indices.push(vbase);
  37048. indices.push(vbase + (i + 2));
  37049. indices.push(vbase + (i + 1));
  37050. }
  37051. }
  37052. };
  37053. // add caps to geometry
  37054. createCylinderCap(false);
  37055. createCylinderCap(true);
  37056. // Sides
  37057. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37058. var vertexData = new VertexData();
  37059. vertexData.indices = indices;
  37060. vertexData.positions = positions;
  37061. vertexData.normals = normals;
  37062. vertexData.uvs = uvs;
  37063. if (faceColors) {
  37064. vertexData.colors = colors;
  37065. }
  37066. return vertexData;
  37067. };
  37068. /**
  37069. * Creates the VertexData for a torus
  37070. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37071. * * diameter the diameter of the torus, optional default 1
  37072. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37073. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37074. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37075. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37076. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37077. * @returns the VertexData of the torus
  37078. */
  37079. VertexData.CreateTorus = function (options) {
  37080. var indices = [];
  37081. var positions = [];
  37082. var normals = [];
  37083. var uvs = [];
  37084. var diameter = options.diameter || 1;
  37085. var thickness = options.thickness || 0.5;
  37086. var tessellation = options.tessellation || 16;
  37087. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37088. var stride = tessellation + 1;
  37089. for (var i = 0; i <= tessellation; i++) {
  37090. var u = i / tessellation;
  37091. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37092. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37093. for (var j = 0; j <= tessellation; j++) {
  37094. var v = 1 - j / tessellation;
  37095. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37096. var dx = Math.cos(innerAngle);
  37097. var dy = Math.sin(innerAngle);
  37098. // Create a vertex.
  37099. var normal = new BABYLON.Vector3(dx, dy, 0);
  37100. var position = normal.scale(thickness / 2);
  37101. var textureCoordinate = new BABYLON.Vector2(u, v);
  37102. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37103. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37104. positions.push(position.x, position.y, position.z);
  37105. normals.push(normal.x, normal.y, normal.z);
  37106. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37107. // And create indices for two triangles.
  37108. var nextI = (i + 1) % stride;
  37109. var nextJ = (j + 1) % stride;
  37110. indices.push(i * stride + j);
  37111. indices.push(i * stride + nextJ);
  37112. indices.push(nextI * stride + j);
  37113. indices.push(i * stride + nextJ);
  37114. indices.push(nextI * stride + nextJ);
  37115. indices.push(nextI * stride + j);
  37116. }
  37117. }
  37118. // Sides
  37119. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37120. // Result
  37121. var vertexData = new VertexData();
  37122. vertexData.indices = indices;
  37123. vertexData.positions = positions;
  37124. vertexData.normals = normals;
  37125. vertexData.uvs = uvs;
  37126. return vertexData;
  37127. };
  37128. /**
  37129. * Creates the VertexData of the LineSystem
  37130. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37131. * - lines an array of lines, each line being an array of successive Vector3
  37132. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37133. * @returns the VertexData of the LineSystem
  37134. */
  37135. VertexData.CreateLineSystem = function (options) {
  37136. var indices = [];
  37137. var positions = [];
  37138. var lines = options.lines;
  37139. var colors = options.colors;
  37140. var vertexColors = [];
  37141. var idx = 0;
  37142. for (var l = 0; l < lines.length; l++) {
  37143. var points = lines[l];
  37144. for (var index = 0; index < points.length; index++) {
  37145. positions.push(points[index].x, points[index].y, points[index].z);
  37146. if (colors) {
  37147. var color = colors[l];
  37148. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37149. }
  37150. if (index > 0) {
  37151. indices.push(idx - 1);
  37152. indices.push(idx);
  37153. }
  37154. idx++;
  37155. }
  37156. }
  37157. var vertexData = new VertexData();
  37158. vertexData.indices = indices;
  37159. vertexData.positions = positions;
  37160. if (colors) {
  37161. vertexData.colors = vertexColors;
  37162. }
  37163. return vertexData;
  37164. };
  37165. /**
  37166. * Create the VertexData for a DashedLines
  37167. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37168. * - points an array successive Vector3
  37169. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37170. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37171. * - dashNb the intended total number of dashes, optional, default 200
  37172. * @returns the VertexData for the DashedLines
  37173. */
  37174. VertexData.CreateDashedLines = function (options) {
  37175. var dashSize = options.dashSize || 3;
  37176. var gapSize = options.gapSize || 1;
  37177. var dashNb = options.dashNb || 200;
  37178. var points = options.points;
  37179. var positions = new Array();
  37180. var indices = new Array();
  37181. var curvect = BABYLON.Vector3.Zero();
  37182. var lg = 0;
  37183. var nb = 0;
  37184. var shft = 0;
  37185. var dashshft = 0;
  37186. var curshft = 0;
  37187. var idx = 0;
  37188. var i = 0;
  37189. for (i = 0; i < points.length - 1; i++) {
  37190. points[i + 1].subtractToRef(points[i], curvect);
  37191. lg += curvect.length();
  37192. }
  37193. shft = lg / dashNb;
  37194. dashshft = dashSize * shft / (dashSize + gapSize);
  37195. for (i = 0; i < points.length - 1; i++) {
  37196. points[i + 1].subtractToRef(points[i], curvect);
  37197. nb = Math.floor(curvect.length() / shft);
  37198. curvect.normalize();
  37199. for (var j = 0; j < nb; j++) {
  37200. curshft = shft * j;
  37201. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37202. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37203. indices.push(idx, idx + 1);
  37204. idx += 2;
  37205. }
  37206. }
  37207. // Result
  37208. var vertexData = new VertexData();
  37209. vertexData.positions = positions;
  37210. vertexData.indices = indices;
  37211. return vertexData;
  37212. };
  37213. /**
  37214. * Creates the VertexData for a Ground
  37215. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37216. * - width the width (x direction) of the ground, optional, default 1
  37217. * - height the height (z direction) of the ground, optional, default 1
  37218. * - subdivisions the number of subdivisions per side, optional, default 1
  37219. * @returns the VertexData of the Ground
  37220. */
  37221. VertexData.CreateGround = function (options) {
  37222. var indices = [];
  37223. var positions = [];
  37224. var normals = [];
  37225. var uvs = [];
  37226. var row, col;
  37227. var width = options.width || 1;
  37228. var height = options.height || 1;
  37229. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37230. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37231. for (row = 0; row <= subdivisionsY; row++) {
  37232. for (col = 0; col <= subdivisionsX; col++) {
  37233. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37234. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37235. positions.push(position.x, position.y, position.z);
  37236. normals.push(normal.x, normal.y, normal.z);
  37237. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37238. }
  37239. }
  37240. for (row = 0; row < subdivisionsY; row++) {
  37241. for (col = 0; col < subdivisionsX; col++) {
  37242. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37243. indices.push(col + 1 + row * (subdivisionsX + 1));
  37244. indices.push(col + row * (subdivisionsX + 1));
  37245. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37246. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37247. indices.push(col + row * (subdivisionsX + 1));
  37248. }
  37249. }
  37250. // Result
  37251. var vertexData = new VertexData();
  37252. vertexData.indices = indices;
  37253. vertexData.positions = positions;
  37254. vertexData.normals = normals;
  37255. vertexData.uvs = uvs;
  37256. return vertexData;
  37257. };
  37258. /**
  37259. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37260. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37261. * * xmin the ground minimum X coordinate, optional, default -1
  37262. * * zmin the ground minimum Z coordinate, optional, default -1
  37263. * * xmax the ground maximum X coordinate, optional, default 1
  37264. * * zmax the ground maximum Z coordinate, optional, default 1
  37265. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37266. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37267. * @returns the VertexData of the TiledGround
  37268. */
  37269. VertexData.CreateTiledGround = function (options) {
  37270. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37271. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37272. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37273. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37274. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37275. var precision = options.precision || { w: 1, h: 1 };
  37276. var indices = new Array();
  37277. var positions = new Array();
  37278. var normals = new Array();
  37279. var uvs = new Array();
  37280. var row, col, tileRow, tileCol;
  37281. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37282. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37283. precision.w = (precision.w < 1) ? 1 : precision.w;
  37284. precision.h = (precision.h < 1) ? 1 : precision.h;
  37285. var tileSize = {
  37286. 'w': (xmax - xmin) / subdivisions.w,
  37287. 'h': (zmax - zmin) / subdivisions.h
  37288. };
  37289. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37290. // Indices
  37291. var base = positions.length / 3;
  37292. var rowLength = precision.w + 1;
  37293. for (row = 0; row < precision.h; row++) {
  37294. for (col = 0; col < precision.w; col++) {
  37295. var square = [
  37296. base + col + row * rowLength,
  37297. base + (col + 1) + row * rowLength,
  37298. base + (col + 1) + (row + 1) * rowLength,
  37299. base + col + (row + 1) * rowLength
  37300. ];
  37301. indices.push(square[1]);
  37302. indices.push(square[2]);
  37303. indices.push(square[3]);
  37304. indices.push(square[0]);
  37305. indices.push(square[1]);
  37306. indices.push(square[3]);
  37307. }
  37308. }
  37309. // Position, normals and uvs
  37310. var position = BABYLON.Vector3.Zero();
  37311. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37312. for (row = 0; row <= precision.h; row++) {
  37313. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37314. for (col = 0; col <= precision.w; col++) {
  37315. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37316. position.y = 0;
  37317. positions.push(position.x, position.y, position.z);
  37318. normals.push(normal.x, normal.y, normal.z);
  37319. uvs.push(col / precision.w, row / precision.h);
  37320. }
  37321. }
  37322. }
  37323. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37324. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37325. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37326. }
  37327. }
  37328. // Result
  37329. var vertexData = new VertexData();
  37330. vertexData.indices = indices;
  37331. vertexData.positions = positions;
  37332. vertexData.normals = normals;
  37333. vertexData.uvs = uvs;
  37334. return vertexData;
  37335. };
  37336. /**
  37337. * Creates the VertexData of the Ground designed from a heightmap
  37338. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37339. * * width the width (x direction) of the ground
  37340. * * height the height (z direction) of the ground
  37341. * * subdivisions the number of subdivisions per side
  37342. * * minHeight the minimum altitude on the ground, optional, default 0
  37343. * * maxHeight the maximum altitude on the ground, optional default 1
  37344. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37345. * * buffer the array holding the image color data
  37346. * * bufferWidth the width of image
  37347. * * bufferHeight the height of image
  37348. * @returns the VertexData of the Ground designed from a heightmap
  37349. */
  37350. VertexData.CreateGroundFromHeightMap = function (options) {
  37351. var indices = [];
  37352. var positions = [];
  37353. var normals = [];
  37354. var uvs = [];
  37355. var row, col;
  37356. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37357. // Vertices
  37358. for (row = 0; row <= options.subdivisions; row++) {
  37359. for (col = 0; col <= options.subdivisions; col++) {
  37360. 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));
  37361. // Compute height
  37362. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37363. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37364. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37365. var r = options.buffer[pos] / 255.0;
  37366. var g = options.buffer[pos + 1] / 255.0;
  37367. var b = options.buffer[pos + 2] / 255.0;
  37368. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37369. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37370. // Add vertex
  37371. positions.push(position.x, position.y, position.z);
  37372. normals.push(0, 0, 0);
  37373. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37374. }
  37375. }
  37376. // Indices
  37377. for (row = 0; row < options.subdivisions; row++) {
  37378. for (col = 0; col < options.subdivisions; col++) {
  37379. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37380. indices.push(col + 1 + row * (options.subdivisions + 1));
  37381. indices.push(col + row * (options.subdivisions + 1));
  37382. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37383. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37384. indices.push(col + row * (options.subdivisions + 1));
  37385. }
  37386. }
  37387. // Normals
  37388. VertexData.ComputeNormals(positions, indices, normals);
  37389. // Result
  37390. var vertexData = new VertexData();
  37391. vertexData.indices = indices;
  37392. vertexData.positions = positions;
  37393. vertexData.normals = normals;
  37394. vertexData.uvs = uvs;
  37395. return vertexData;
  37396. };
  37397. /**
  37398. * Creates the VertexData for a Plane
  37399. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37400. * * size sets the width and height of the plane to the value of size, optional default 1
  37401. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37402. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37403. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37404. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37405. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37406. * @returns the VertexData of the box
  37407. */
  37408. VertexData.CreatePlane = function (options) {
  37409. var indices = [];
  37410. var positions = [];
  37411. var normals = [];
  37412. var uvs = [];
  37413. var width = options.width || options.size || 1;
  37414. var height = options.height || options.size || 1;
  37415. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37416. // Vertices
  37417. var halfWidth = width / 2.0;
  37418. var halfHeight = height / 2.0;
  37419. positions.push(-halfWidth, -halfHeight, 0);
  37420. normals.push(0, 0, -1.0);
  37421. uvs.push(0.0, 0.0);
  37422. positions.push(halfWidth, -halfHeight, 0);
  37423. normals.push(0, 0, -1.0);
  37424. uvs.push(1.0, 0.0);
  37425. positions.push(halfWidth, halfHeight, 0);
  37426. normals.push(0, 0, -1.0);
  37427. uvs.push(1.0, 1.0);
  37428. positions.push(-halfWidth, halfHeight, 0);
  37429. normals.push(0, 0, -1.0);
  37430. uvs.push(0.0, 1.0);
  37431. // Indices
  37432. indices.push(0);
  37433. indices.push(1);
  37434. indices.push(2);
  37435. indices.push(0);
  37436. indices.push(2);
  37437. indices.push(3);
  37438. // Sides
  37439. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37440. // Result
  37441. var vertexData = new VertexData();
  37442. vertexData.indices = indices;
  37443. vertexData.positions = positions;
  37444. vertexData.normals = normals;
  37445. vertexData.uvs = uvs;
  37446. return vertexData;
  37447. };
  37448. /**
  37449. * Creates the VertexData of the Disc or regular Polygon
  37450. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37451. * * radius the radius of the disc, optional default 0.5
  37452. * * tessellation the number of polygon sides, optional, default 64
  37453. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37454. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37455. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37456. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37457. * @returns the VertexData of the box
  37458. */
  37459. VertexData.CreateDisc = function (options) {
  37460. var positions = new Array();
  37461. var indices = new Array();
  37462. var normals = new Array();
  37463. var uvs = new Array();
  37464. var radius = options.radius || 0.5;
  37465. var tessellation = options.tessellation || 64;
  37466. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37467. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37468. // positions and uvs
  37469. positions.push(0, 0, 0); // disc center first
  37470. uvs.push(0.5, 0.5);
  37471. var theta = Math.PI * 2 * arc;
  37472. var step = theta / tessellation;
  37473. for (var a = 0; a < theta; a += step) {
  37474. var x = Math.cos(a);
  37475. var y = Math.sin(a);
  37476. var u = (x + 1) / 2;
  37477. var v = (1 - y) / 2;
  37478. positions.push(radius * x, radius * y, 0);
  37479. uvs.push(u, v);
  37480. }
  37481. if (arc === 1) {
  37482. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37483. uvs.push(uvs[2], uvs[3]);
  37484. }
  37485. //indices
  37486. var vertexNb = positions.length / 3;
  37487. for (var i = 1; i < vertexNb - 1; i++) {
  37488. indices.push(i + 1, 0, i);
  37489. }
  37490. // result
  37491. VertexData.ComputeNormals(positions, indices, normals);
  37492. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37493. var vertexData = new VertexData();
  37494. vertexData.indices = indices;
  37495. vertexData.positions = positions;
  37496. vertexData.normals = normals;
  37497. vertexData.uvs = uvs;
  37498. return vertexData;
  37499. };
  37500. /**
  37501. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37502. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37503. * @param polygon a mesh built from polygonTriangulation.build()
  37504. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37505. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37506. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37507. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37508. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37509. * @returns the VertexData of the Polygon
  37510. */
  37511. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37512. var faceUV = fUV || new Array(3);
  37513. var faceColors = fColors;
  37514. var colors = [];
  37515. // default face colors and UV if undefined
  37516. for (var f = 0; f < 3; f++) {
  37517. if (faceUV[f] === undefined) {
  37518. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37519. }
  37520. if (faceColors && faceColors[f] === undefined) {
  37521. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37522. }
  37523. }
  37524. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37525. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37526. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37527. var indices = polygon.getIndices();
  37528. // set face colours and textures
  37529. var idx = 0;
  37530. var face = 0;
  37531. for (var index = 0; index < normals.length; index += 3) {
  37532. //Edge Face no. 1
  37533. if (Math.abs(normals[index + 1]) < 0.001) {
  37534. face = 1;
  37535. }
  37536. //Top Face no. 0
  37537. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37538. face = 0;
  37539. }
  37540. //Bottom Face no. 2
  37541. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37542. face = 2;
  37543. }
  37544. idx = index / 3;
  37545. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37546. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37547. if (faceColors) {
  37548. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37549. }
  37550. }
  37551. // sides
  37552. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37553. // Result
  37554. var vertexData = new VertexData();
  37555. vertexData.indices = indices;
  37556. vertexData.positions = positions;
  37557. vertexData.normals = normals;
  37558. vertexData.uvs = uvs;
  37559. if (faceColors) {
  37560. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37561. vertexData.colors = totalColors;
  37562. }
  37563. return vertexData;
  37564. };
  37565. /**
  37566. * Creates the VertexData of the IcoSphere
  37567. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37568. * * radius the radius of the IcoSphere, optional default 1
  37569. * * radiusX allows stretching in the x direction, optional, default radius
  37570. * * radiusY allows stretching in the y direction, optional, default radius
  37571. * * radiusZ allows stretching in the z direction, optional, default radius
  37572. * * flat when true creates a flat shaded mesh, optional, default true
  37573. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37574. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37575. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37576. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37577. * @returns the VertexData of the IcoSphere
  37578. */
  37579. VertexData.CreateIcoSphere = function (options) {
  37580. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37581. var radius = options.radius || 1;
  37582. var flat = (options.flat === undefined) ? true : options.flat;
  37583. var subdivisions = options.subdivisions || 4;
  37584. var radiusX = options.radiusX || radius;
  37585. var radiusY = options.radiusY || radius;
  37586. var radiusZ = options.radiusZ || radius;
  37587. var t = (1 + Math.sqrt(5)) / 2;
  37588. // 12 vertex x,y,z
  37589. var ico_vertices = [
  37590. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37591. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37592. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37593. ];
  37594. // index of 3 vertex makes a face of icopshere
  37595. var ico_indices = [
  37596. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37597. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37598. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37599. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37600. ];
  37601. // vertex for uv have aliased position, not for UV
  37602. var vertices_unalias_id = [
  37603. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37604. // vertex alias
  37605. 0,
  37606. 2,
  37607. 3,
  37608. 3,
  37609. 3,
  37610. 4,
  37611. 7,
  37612. 8,
  37613. 9,
  37614. 9,
  37615. 10,
  37616. 11 // 23: B + 12
  37617. ];
  37618. // uv as integer step (not pixels !)
  37619. var ico_vertexuv = [
  37620. 5, 1, 3, 1, 6, 4, 0, 0,
  37621. 5, 3, 4, 2, 2, 2, 4, 0,
  37622. 2, 0, 1, 1, 6, 0, 6, 2,
  37623. // vertex alias (for same vertex on different faces)
  37624. 0, 4,
  37625. 3, 3,
  37626. 4, 4,
  37627. 3, 1,
  37628. 4, 2,
  37629. 4, 4,
  37630. 0, 2,
  37631. 1, 1,
  37632. 2, 2,
  37633. 3, 3,
  37634. 1, 3,
  37635. 2, 4 // 23: B + 12
  37636. ];
  37637. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37638. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37639. // First island of uv mapping
  37640. // v = 4h 3+ 2
  37641. // v = 3h 9+ 4
  37642. // v = 2h 9+ 5 B
  37643. // v = 1h 9 1 0
  37644. // v = 0h 3 8 7 A
  37645. // u = 0 1 2 3 4 5 6 *a
  37646. // Second island of uv mapping
  37647. // v = 4h 0+ B+ 4+
  37648. // v = 3h A+ 2+
  37649. // v = 2h 7+ 6 3+
  37650. // v = 1h 8+ 3+
  37651. // v = 0h
  37652. // u = 0 1 2 3 4 5 6 *a
  37653. // Face layout on texture UV mapping
  37654. // ============
  37655. // \ 4 /\ 16 / ======
  37656. // \ / \ / /\ 11 /
  37657. // \/ 7 \/ / \ /
  37658. // ======= / 10 \/
  37659. // /\ 17 /\ =======
  37660. // / \ / \ \ 15 /\
  37661. // / 8 \/ 12 \ \ / \
  37662. // ============ \/ 6 \
  37663. // \ 18 /\ ============
  37664. // \ / \ \ 5 /\ 0 /
  37665. // \/ 13 \ \ / \ /
  37666. // ======= \/ 1 \/
  37667. // =============
  37668. // /\ 19 /\ 2 /\
  37669. // / \ / \ / \
  37670. // / 14 \/ 9 \/ 3 \
  37671. // ===================
  37672. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37673. var ustep = 138 / 1024;
  37674. var vstep = 239 / 1024;
  37675. var uoffset = 60 / 1024;
  37676. var voffset = 26 / 1024;
  37677. // Second island should have margin, not to touch the first island
  37678. // avoid any borderline artefact in pixel rounding
  37679. var island_u_offset = -40 / 1024;
  37680. var island_v_offset = +20 / 1024;
  37681. // face is either island 0 or 1 :
  37682. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37683. var island = [
  37684. 0, 0, 0, 0, 1,
  37685. 0, 0, 1, 1, 0,
  37686. 0, 0, 1, 1, 0,
  37687. 0, 1, 1, 1, 0 // 15 - 19
  37688. ];
  37689. var indices = new Array();
  37690. var positions = new Array();
  37691. var normals = new Array();
  37692. var uvs = new Array();
  37693. var current_indice = 0;
  37694. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37695. var face_vertex_pos = new Array(3);
  37696. var face_vertex_uv = new Array(3);
  37697. var v012;
  37698. for (v012 = 0; v012 < 3; v012++) {
  37699. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37700. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37701. }
  37702. // create all with normals
  37703. for (var face = 0; face < 20; face++) {
  37704. // 3 vertex per face
  37705. for (v012 = 0; v012 < 3; v012++) {
  37706. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37707. var v_id = ico_indices[3 * face + v012];
  37708. // vertex have 3D position (x,y,z)
  37709. 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]);
  37710. // Normalize to get normal, then scale to radius
  37711. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37712. // uv Coordinates from vertex ID
  37713. 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);
  37714. }
  37715. // Subdivide the face (interpolate pos, norm, uv)
  37716. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37717. // - norm is linear interpolation of vertex corner normal
  37718. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37719. // - uv is linear interpolation
  37720. //
  37721. // Topology is as below for sub-divide by 2
  37722. // vertex shown as v0,v1,v2
  37723. // interp index is i1 to progress in range [v0,v1[
  37724. // interp index is i2 to progress in range [v0,v2[
  37725. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37726. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37727. //
  37728. //
  37729. // i2 v2
  37730. // ^ ^
  37731. // / / \
  37732. // / / \
  37733. // / / \
  37734. // / / (0,1) \
  37735. // / #---------\
  37736. // / / \ (0,0)'/ \
  37737. // / / \ / \
  37738. // / / \ / \
  37739. // / / (0,0) \ / (1,0) \
  37740. // / #---------#---------\
  37741. // v0 v1
  37742. //
  37743. // --------------------> i1
  37744. //
  37745. // interp of (i1,i2):
  37746. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37747. // along i1 : lerp(x0,x1, i1/(S-i2))
  37748. //
  37749. // centroid of triangle is needed to get help normal computation
  37750. // (c1,c2) are used for centroid location
  37751. var interp_vertex = function (i1, i2, c1, c2) {
  37752. // vertex is interpolated from
  37753. // - face_vertex_pos[0..2]
  37754. // - face_vertex_uv[0..2]
  37755. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37756. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37757. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37758. pos_interp.normalize();
  37759. var vertex_normal;
  37760. if (flat) {
  37761. // in flat mode, recalculate normal as face centroid normal
  37762. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37763. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37764. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37765. }
  37766. else {
  37767. // in smooth mode, recalculate normal from each single vertex position
  37768. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37769. }
  37770. // Vertex normal need correction due to X,Y,Z radius scaling
  37771. vertex_normal.x /= radiusX;
  37772. vertex_normal.y /= radiusY;
  37773. vertex_normal.z /= radiusZ;
  37774. vertex_normal.normalize();
  37775. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37776. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37777. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37778. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37779. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37780. uvs.push(uv_interp.x, uv_interp.y);
  37781. // push each vertex has member of a face
  37782. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37783. indices.push(current_indice);
  37784. current_indice++;
  37785. };
  37786. for (var i2 = 0; i2 < subdivisions; i2++) {
  37787. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37788. // face : (i1,i2) for /\ :
  37789. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37790. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37791. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37792. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37793. if (i1 + i2 + 1 < subdivisions) {
  37794. // face : (i1,i2)' for \/ :
  37795. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37796. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37797. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37798. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37799. }
  37800. }
  37801. }
  37802. }
  37803. // Sides
  37804. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37805. // Result
  37806. var vertexData = new VertexData();
  37807. vertexData.indices = indices;
  37808. vertexData.positions = positions;
  37809. vertexData.normals = normals;
  37810. vertexData.uvs = uvs;
  37811. return vertexData;
  37812. };
  37813. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37814. /**
  37815. * Creates the VertexData for a Polyhedron
  37816. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37817. * * type provided types are:
  37818. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37819. * * 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)
  37820. * * size the size of the IcoSphere, optional default 1
  37821. * * sizeX allows stretching in the x direction, optional, default size
  37822. * * sizeY allows stretching in the y direction, optional, default size
  37823. * * sizeZ allows stretching in the z direction, optional, default size
  37824. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  37825. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37826. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37827. * * flat when true creates a flat shaded mesh, optional, default true
  37828. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37829. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37830. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37831. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37832. * @returns the VertexData of the Polyhedron
  37833. */
  37834. VertexData.CreatePolyhedron = function (options) {
  37835. // provided polyhedron types :
  37836. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37837. // 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)
  37838. var polyhedra = [];
  37839. 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]] };
  37840. 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]] };
  37841. polyhedra[2] = {
  37842. 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]],
  37843. 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]]
  37844. };
  37845. polyhedra[3] = {
  37846. 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]],
  37847. 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]]
  37848. };
  37849. polyhedra[4] = {
  37850. 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]],
  37851. 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]]
  37852. };
  37853. 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]] };
  37854. 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]] };
  37855. 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]] };
  37856. 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]] };
  37857. 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]] };
  37858. 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]] };
  37859. 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]] };
  37860. 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]] };
  37861. 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]] };
  37862. polyhedra[14] = {
  37863. 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]],
  37864. 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]]
  37865. };
  37866. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37867. var size = options.size;
  37868. var sizeX = options.sizeX || size || 1;
  37869. var sizeY = options.sizeY || size || 1;
  37870. var sizeZ = options.sizeZ || size || 1;
  37871. var data = options.custom || polyhedra[type];
  37872. var nbfaces = data.face.length;
  37873. var faceUV = options.faceUV || new Array(nbfaces);
  37874. var faceColors = options.faceColors;
  37875. var flat = (options.flat === undefined) ? true : options.flat;
  37876. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37877. var positions = new Array();
  37878. var indices = new Array();
  37879. var normals = new Array();
  37880. var uvs = new Array();
  37881. var colors = new Array();
  37882. var index = 0;
  37883. var faceIdx = 0; // face cursor in the array "indexes"
  37884. var indexes = new Array();
  37885. var i = 0;
  37886. var f = 0;
  37887. var u, v, ang, x, y, tmp;
  37888. // default face colors and UV if undefined
  37889. if (flat) {
  37890. for (f = 0; f < nbfaces; f++) {
  37891. if (faceColors && faceColors[f] === undefined) {
  37892. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37893. }
  37894. if (faceUV && faceUV[f] === undefined) {
  37895. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37896. }
  37897. }
  37898. }
  37899. if (!flat) {
  37900. for (i = 0; i < data.vertex.length; i++) {
  37901. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37902. uvs.push(0, 0);
  37903. }
  37904. for (f = 0; f < nbfaces; f++) {
  37905. for (i = 0; i < data.face[f].length - 2; i++) {
  37906. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37907. }
  37908. }
  37909. }
  37910. else {
  37911. for (f = 0; f < nbfaces; f++) {
  37912. var fl = data.face[f].length; // number of vertices of the current face
  37913. ang = 2 * Math.PI / fl;
  37914. x = 0.5 * Math.tan(ang / 2);
  37915. y = 0.5;
  37916. // positions, uvs, colors
  37917. for (i = 0; i < fl; i++) {
  37918. // positions
  37919. 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);
  37920. indexes.push(index);
  37921. index++;
  37922. // uvs
  37923. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37924. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37925. uvs.push(u, v);
  37926. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37927. y = x * Math.sin(ang) + y * Math.cos(ang);
  37928. x = tmp;
  37929. // colors
  37930. if (faceColors) {
  37931. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37932. }
  37933. }
  37934. // indices from indexes
  37935. for (i = 0; i < fl - 2; i++) {
  37936. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37937. }
  37938. faceIdx += fl;
  37939. }
  37940. }
  37941. VertexData.ComputeNormals(positions, indices, normals);
  37942. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37943. var vertexData = new VertexData();
  37944. vertexData.positions = positions;
  37945. vertexData.indices = indices;
  37946. vertexData.normals = normals;
  37947. vertexData.uvs = uvs;
  37948. if (faceColors && flat) {
  37949. vertexData.colors = colors;
  37950. }
  37951. return vertexData;
  37952. };
  37953. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37954. /**
  37955. * Creates the VertexData for a TorusKnot
  37956. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37957. * * radius the radius of the torus knot, optional, default 2
  37958. * * tube the thickness of the tube, optional, default 0.5
  37959. * * radialSegments the number of sides on each tube segments, optional, default 32
  37960. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37961. * * p the number of windings around the z axis, optional, default 2
  37962. * * q the number of windings around the x axis, optional, default 3
  37963. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37964. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37965. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37966. * @returns the VertexData of the Torus Knot
  37967. */
  37968. VertexData.CreateTorusKnot = function (options) {
  37969. var indices = new Array();
  37970. var positions = new Array();
  37971. var normals = new Array();
  37972. var uvs = new Array();
  37973. var radius = options.radius || 2;
  37974. var tube = options.tube || 0.5;
  37975. var radialSegments = options.radialSegments || 32;
  37976. var tubularSegments = options.tubularSegments || 32;
  37977. var p = options.p || 2;
  37978. var q = options.q || 3;
  37979. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37980. // Helper
  37981. var getPos = function (angle) {
  37982. var cu = Math.cos(angle);
  37983. var su = Math.sin(angle);
  37984. var quOverP = q / p * angle;
  37985. var cs = Math.cos(quOverP);
  37986. var tx = radius * (2 + cs) * 0.5 * cu;
  37987. var ty = radius * (2 + cs) * su * 0.5;
  37988. var tz = radius * Math.sin(quOverP) * 0.5;
  37989. return new BABYLON.Vector3(tx, ty, tz);
  37990. };
  37991. // Vertices
  37992. var i;
  37993. var j;
  37994. for (i = 0; i <= radialSegments; i++) {
  37995. var modI = i % radialSegments;
  37996. var u = modI / radialSegments * 2 * p * Math.PI;
  37997. var p1 = getPos(u);
  37998. var p2 = getPos(u + 0.01);
  37999. var tang = p2.subtract(p1);
  38000. var n = p2.add(p1);
  38001. var bitan = BABYLON.Vector3.Cross(tang, n);
  38002. n = BABYLON.Vector3.Cross(bitan, tang);
  38003. bitan.normalize();
  38004. n.normalize();
  38005. for (j = 0; j < tubularSegments; j++) {
  38006. var modJ = j % tubularSegments;
  38007. var v = modJ / tubularSegments * 2 * Math.PI;
  38008. var cx = -tube * Math.cos(v);
  38009. var cy = tube * Math.sin(v);
  38010. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38011. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38012. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38013. uvs.push(i / radialSegments);
  38014. uvs.push(j / tubularSegments);
  38015. }
  38016. }
  38017. for (i = 0; i < radialSegments; i++) {
  38018. for (j = 0; j < tubularSegments; j++) {
  38019. var jNext = (j + 1) % tubularSegments;
  38020. var a = i * tubularSegments + j;
  38021. var b = (i + 1) * tubularSegments + j;
  38022. var c = (i + 1) * tubularSegments + jNext;
  38023. var d = i * tubularSegments + jNext;
  38024. indices.push(d);
  38025. indices.push(b);
  38026. indices.push(a);
  38027. indices.push(d);
  38028. indices.push(c);
  38029. indices.push(b);
  38030. }
  38031. }
  38032. // Normals
  38033. VertexData.ComputeNormals(positions, indices, normals);
  38034. // Sides
  38035. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38036. // Result
  38037. var vertexData = new VertexData();
  38038. vertexData.indices = indices;
  38039. vertexData.positions = positions;
  38040. vertexData.normals = normals;
  38041. vertexData.uvs = uvs;
  38042. return vertexData;
  38043. };
  38044. // Tools
  38045. /**
  38046. * Compute normals for given positions and indices
  38047. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38048. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38049. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38050. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38051. * * facetNormals : optional array of facet normals (vector3)
  38052. * * facetPositions : optional array of facet positions (vector3)
  38053. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38054. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38055. * * bInfo : optional bounding info, required for facetPartitioning computation
  38056. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38057. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38058. * * useRightHandedSystem: optional boolean to for right handed system computation
  38059. * * depthSort : optional boolean to enable the facet depth sort computation
  38060. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38061. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38062. */
  38063. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38064. // temporary scalar variables
  38065. var index = 0; // facet index
  38066. var p1p2x = 0.0; // p1p2 vector x coordinate
  38067. var p1p2y = 0.0; // p1p2 vector y coordinate
  38068. var p1p2z = 0.0; // p1p2 vector z coordinate
  38069. var p3p2x = 0.0; // p3p2 vector x coordinate
  38070. var p3p2y = 0.0; // p3p2 vector y coordinate
  38071. var p3p2z = 0.0; // p3p2 vector z coordinate
  38072. var faceNormalx = 0.0; // facet normal x coordinate
  38073. var faceNormaly = 0.0; // facet normal y coordinate
  38074. var faceNormalz = 0.0; // facet normal z coordinate
  38075. var length = 0.0; // facet normal length before normalization
  38076. var v1x = 0; // vector1 x index in the positions array
  38077. var v1y = 0; // vector1 y index in the positions array
  38078. var v1z = 0; // vector1 z index in the positions array
  38079. var v2x = 0; // vector2 x index in the positions array
  38080. var v2y = 0; // vector2 y index in the positions array
  38081. var v2z = 0; // vector2 z index in the positions array
  38082. var v3x = 0; // vector3 x index in the positions array
  38083. var v3y = 0; // vector3 y index in the positions array
  38084. var v3z = 0; // vector3 z index in the positions array
  38085. var computeFacetNormals = false;
  38086. var computeFacetPositions = false;
  38087. var computeFacetPartitioning = false;
  38088. var computeDepthSort = false;
  38089. var faceNormalSign = 1;
  38090. var ratio = 0;
  38091. var distanceTo = null;
  38092. if (options) {
  38093. computeFacetNormals = (options.facetNormals) ? true : false;
  38094. computeFacetPositions = (options.facetPositions) ? true : false;
  38095. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38096. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38097. ratio = options.ratio || 0;
  38098. computeDepthSort = (options.depthSort) ? true : false;
  38099. distanceTo = (options.distanceTo);
  38100. if (computeDepthSort) {
  38101. if (distanceTo === undefined) {
  38102. distanceTo = BABYLON.Vector3.Zero();
  38103. }
  38104. var depthSortedFacets = options.depthSortedFacets;
  38105. }
  38106. }
  38107. // facetPartitioning reinit if needed
  38108. var xSubRatio = 0;
  38109. var ySubRatio = 0;
  38110. var zSubRatio = 0;
  38111. var subSq = 0;
  38112. if (computeFacetPartitioning && options && options.bbSize) {
  38113. var ox = 0; // X partitioning index for facet position
  38114. var oy = 0; // Y partinioning index for facet position
  38115. var oz = 0; // Z partinioning index for facet position
  38116. var b1x = 0; // X partitioning index for facet v1 vertex
  38117. var b1y = 0; // Y partitioning index for facet v1 vertex
  38118. var b1z = 0; // z partitioning index for facet v1 vertex
  38119. var b2x = 0; // X partitioning index for facet v2 vertex
  38120. var b2y = 0; // Y partitioning index for facet v2 vertex
  38121. var b2z = 0; // Z partitioning index for facet v2 vertex
  38122. var b3x = 0; // X partitioning index for facet v3 vertex
  38123. var b3y = 0; // Y partitioning index for facet v3 vertex
  38124. var b3z = 0; // Z partitioning index for facet v3 vertex
  38125. var block_idx_o = 0; // facet barycenter block index
  38126. var block_idx_v1 = 0; // v1 vertex block index
  38127. var block_idx_v2 = 0; // v2 vertex block index
  38128. var block_idx_v3 = 0; // v3 vertex block index
  38129. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38130. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38131. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38132. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38133. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38134. subSq = options.subDiv.max * options.subDiv.max;
  38135. options.facetPartitioning.length = 0;
  38136. }
  38137. // reset the normals
  38138. for (index = 0; index < positions.length; index++) {
  38139. normals[index] = 0.0;
  38140. }
  38141. // Loop : 1 indice triplet = 1 facet
  38142. var nbFaces = (indices.length / 3) | 0;
  38143. for (index = 0; index < nbFaces; index++) {
  38144. // get the indexes of the coordinates of each vertex of the facet
  38145. v1x = indices[index * 3] * 3;
  38146. v1y = v1x + 1;
  38147. v1z = v1x + 2;
  38148. v2x = indices[index * 3 + 1] * 3;
  38149. v2y = v2x + 1;
  38150. v2z = v2x + 2;
  38151. v3x = indices[index * 3 + 2] * 3;
  38152. v3y = v3x + 1;
  38153. v3z = v3x + 2;
  38154. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38155. p1p2y = positions[v1y] - positions[v2y];
  38156. p1p2z = positions[v1z] - positions[v2z];
  38157. p3p2x = positions[v3x] - positions[v2x];
  38158. p3p2y = positions[v3y] - positions[v2y];
  38159. p3p2z = positions[v3z] - positions[v2z];
  38160. // compute the face normal with the cross product
  38161. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38162. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38163. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38164. // normalize this normal and store it in the array facetData
  38165. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38166. length = (length === 0) ? 1.0 : length;
  38167. faceNormalx /= length;
  38168. faceNormaly /= length;
  38169. faceNormalz /= length;
  38170. if (computeFacetNormals && options) {
  38171. options.facetNormals[index].x = faceNormalx;
  38172. options.facetNormals[index].y = faceNormaly;
  38173. options.facetNormals[index].z = faceNormalz;
  38174. }
  38175. if (computeFacetPositions && options) {
  38176. // compute and the facet barycenter coordinates in the array facetPositions
  38177. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38178. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38179. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38180. }
  38181. if (computeFacetPartitioning && options) {
  38182. // store the facet indexes in arrays in the main facetPartitioning array :
  38183. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38184. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38185. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38186. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38187. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38188. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38189. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38190. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38191. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38192. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38193. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38194. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38195. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38196. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38197. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38198. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38199. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38200. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38201. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38202. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38203. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38204. // push each facet index in each block containing the vertex
  38205. options.facetPartitioning[block_idx_v1].push(index);
  38206. if (block_idx_v2 != block_idx_v1) {
  38207. options.facetPartitioning[block_idx_v2].push(index);
  38208. }
  38209. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38210. options.facetPartitioning[block_idx_v3].push(index);
  38211. }
  38212. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38213. options.facetPartitioning[block_idx_o].push(index);
  38214. }
  38215. }
  38216. if (computeDepthSort && options && options.facetPositions) {
  38217. var dsf = depthSortedFacets[index];
  38218. dsf.ind = index * 3;
  38219. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38220. }
  38221. // compute the normals anyway
  38222. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38223. normals[v1y] += faceNormaly;
  38224. normals[v1z] += faceNormalz;
  38225. normals[v2x] += faceNormalx;
  38226. normals[v2y] += faceNormaly;
  38227. normals[v2z] += faceNormalz;
  38228. normals[v3x] += faceNormalx;
  38229. normals[v3y] += faceNormaly;
  38230. normals[v3z] += faceNormalz;
  38231. }
  38232. // last normalization of each normal
  38233. for (index = 0; index < normals.length / 3; index++) {
  38234. faceNormalx = normals[index * 3];
  38235. faceNormaly = normals[index * 3 + 1];
  38236. faceNormalz = normals[index * 3 + 2];
  38237. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38238. length = (length === 0) ? 1.0 : length;
  38239. faceNormalx /= length;
  38240. faceNormaly /= length;
  38241. faceNormalz /= length;
  38242. normals[index * 3] = faceNormalx;
  38243. normals[index * 3 + 1] = faceNormaly;
  38244. normals[index * 3 + 2] = faceNormalz;
  38245. }
  38246. };
  38247. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38248. var li = indices.length;
  38249. var ln = normals.length;
  38250. var i;
  38251. var n;
  38252. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38253. switch (sideOrientation) {
  38254. case BABYLON.Mesh.FRONTSIDE:
  38255. // nothing changed
  38256. break;
  38257. case BABYLON.Mesh.BACKSIDE:
  38258. var tmp;
  38259. // indices
  38260. for (i = 0; i < li; i += 3) {
  38261. tmp = indices[i];
  38262. indices[i] = indices[i + 2];
  38263. indices[i + 2] = tmp;
  38264. }
  38265. // normals
  38266. for (n = 0; n < ln; n++) {
  38267. normals[n] = -normals[n];
  38268. }
  38269. break;
  38270. case BABYLON.Mesh.DOUBLESIDE:
  38271. // positions
  38272. var lp = positions.length;
  38273. var l = lp / 3;
  38274. for (var p = 0; p < lp; p++) {
  38275. positions[lp + p] = positions[p];
  38276. }
  38277. // indices
  38278. for (i = 0; i < li; i += 3) {
  38279. indices[i + li] = indices[i + 2] + l;
  38280. indices[i + 1 + li] = indices[i + 1] + l;
  38281. indices[i + 2 + li] = indices[i] + l;
  38282. }
  38283. // normals
  38284. for (n = 0; n < ln; n++) {
  38285. normals[ln + n] = -normals[n];
  38286. }
  38287. // uvs
  38288. var lu = uvs.length;
  38289. var u = 0;
  38290. for (u = 0; u < lu; u++) {
  38291. uvs[u + lu] = uvs[u];
  38292. }
  38293. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38294. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38295. u = 0;
  38296. for (i = 0; i < lu / 2; i++) {
  38297. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38298. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38299. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38300. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38301. u += 2;
  38302. }
  38303. break;
  38304. }
  38305. };
  38306. /**
  38307. * Applies VertexData created from the imported parameters to the geometry
  38308. * @param parsedVertexData the parsed data from an imported file
  38309. * @param geometry the geometry to apply the VertexData to
  38310. */
  38311. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38312. var vertexData = new VertexData();
  38313. // positions
  38314. var positions = parsedVertexData.positions;
  38315. if (positions) {
  38316. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38317. }
  38318. // normals
  38319. var normals = parsedVertexData.normals;
  38320. if (normals) {
  38321. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38322. }
  38323. // tangents
  38324. var tangents = parsedVertexData.tangents;
  38325. if (tangents) {
  38326. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38327. }
  38328. // uvs
  38329. var uvs = parsedVertexData.uvs;
  38330. if (uvs) {
  38331. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38332. }
  38333. // uv2s
  38334. var uv2s = parsedVertexData.uv2s;
  38335. if (uv2s) {
  38336. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38337. }
  38338. // uv3s
  38339. var uv3s = parsedVertexData.uv3s;
  38340. if (uv3s) {
  38341. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38342. }
  38343. // uv4s
  38344. var uv4s = parsedVertexData.uv4s;
  38345. if (uv4s) {
  38346. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38347. }
  38348. // uv5s
  38349. var uv5s = parsedVertexData.uv5s;
  38350. if (uv5s) {
  38351. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38352. }
  38353. // uv6s
  38354. var uv6s = parsedVertexData.uv6s;
  38355. if (uv6s) {
  38356. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38357. }
  38358. // colors
  38359. var colors = parsedVertexData.colors;
  38360. if (colors) {
  38361. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38362. }
  38363. // matricesIndices
  38364. var matricesIndices = parsedVertexData.matricesIndices;
  38365. if (matricesIndices) {
  38366. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38367. }
  38368. // matricesWeights
  38369. var matricesWeights = parsedVertexData.matricesWeights;
  38370. if (matricesWeights) {
  38371. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38372. }
  38373. // indices
  38374. var indices = parsedVertexData.indices;
  38375. if (indices) {
  38376. vertexData.indices = indices;
  38377. }
  38378. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38379. };
  38380. return VertexData;
  38381. }());
  38382. BABYLON.VertexData = VertexData;
  38383. })(BABYLON || (BABYLON = {}));
  38384. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38385. var BABYLON;
  38386. (function (BABYLON) {
  38387. /**
  38388. * Class used to store geometry data (vertex buffers + index buffer)
  38389. */
  38390. var Geometry = /** @class */ (function () {
  38391. /**
  38392. * Creates a new geometry
  38393. * @param id defines the unique ID
  38394. * @param scene defines the hosting scene
  38395. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38396. * @param updatable defines if geometry must be updatable (false by default)
  38397. * @param mesh defines the mesh that will be associated with the geometry
  38398. */
  38399. function Geometry(id, scene, vertexData, updatable, mesh) {
  38400. if (updatable === void 0) { updatable = false; }
  38401. if (mesh === void 0) { mesh = null; }
  38402. /**
  38403. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38404. */
  38405. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38406. this._totalVertices = 0;
  38407. this._isDisposed = false;
  38408. this._indexBufferIsUpdatable = false;
  38409. this.id = id;
  38410. this._engine = scene.getEngine();
  38411. this._meshes = [];
  38412. this._scene = scene;
  38413. //Init vertex buffer cache
  38414. this._vertexBuffers = {};
  38415. this._indices = [];
  38416. this._updatable = updatable;
  38417. // vertexData
  38418. if (vertexData) {
  38419. this.setAllVerticesData(vertexData, updatable);
  38420. }
  38421. else {
  38422. this._totalVertices = 0;
  38423. this._indices = [];
  38424. }
  38425. if (this._engine.getCaps().vertexArrayObject) {
  38426. this._vertexArrayObjects = {};
  38427. }
  38428. // applyToMesh
  38429. if (mesh) {
  38430. if (mesh.getClassName() === "LinesMesh") {
  38431. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38432. this._updateExtend();
  38433. }
  38434. this.applyToMesh(mesh);
  38435. mesh.computeWorldMatrix(true);
  38436. }
  38437. }
  38438. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38439. /**
  38440. * 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
  38441. */
  38442. get: function () {
  38443. return this._boundingBias;
  38444. },
  38445. /**
  38446. * 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
  38447. */
  38448. set: function (value) {
  38449. if (this._boundingBias && this._boundingBias.equals(value)) {
  38450. return;
  38451. }
  38452. this._boundingBias = value.clone();
  38453. this._updateBoundingInfo(true, null);
  38454. },
  38455. enumerable: true,
  38456. configurable: true
  38457. });
  38458. /**
  38459. * Static function used to attach a new empty geometry to a mesh
  38460. * @param mesh defines the mesh to attach the geometry to
  38461. * @returns the new {BABYLON.Geometry}
  38462. */
  38463. Geometry.CreateGeometryForMesh = function (mesh) {
  38464. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38465. geometry.applyToMesh(mesh);
  38466. return geometry;
  38467. };
  38468. Object.defineProperty(Geometry.prototype, "extend", {
  38469. /**
  38470. * Gets the current extend of the geometry
  38471. */
  38472. get: function () {
  38473. return this._extend;
  38474. },
  38475. enumerable: true,
  38476. configurable: true
  38477. });
  38478. /**
  38479. * Gets the hosting scene
  38480. * @returns the hosting {BABYLON.Scene}
  38481. */
  38482. Geometry.prototype.getScene = function () {
  38483. return this._scene;
  38484. };
  38485. /**
  38486. * Gets the hosting engine
  38487. * @returns the hosting {BABYLON.Engine}
  38488. */
  38489. Geometry.prototype.getEngine = function () {
  38490. return this._engine;
  38491. };
  38492. /**
  38493. * Defines if the geometry is ready to use
  38494. * @returns true if the geometry is ready to be used
  38495. */
  38496. Geometry.prototype.isReady = function () {
  38497. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38498. };
  38499. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38500. /**
  38501. * Gets a value indicating that the geometry should not be serialized
  38502. */
  38503. get: function () {
  38504. for (var index = 0; index < this._meshes.length; index++) {
  38505. if (!this._meshes[index].doNotSerialize) {
  38506. return false;
  38507. }
  38508. }
  38509. return true;
  38510. },
  38511. enumerable: true,
  38512. configurable: true
  38513. });
  38514. /** @hidden */
  38515. Geometry.prototype._rebuild = function () {
  38516. if (this._vertexArrayObjects) {
  38517. this._vertexArrayObjects = {};
  38518. }
  38519. // Index buffer
  38520. if (this._meshes.length !== 0 && this._indices) {
  38521. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38522. }
  38523. // Vertex buffers
  38524. for (var key in this._vertexBuffers) {
  38525. var vertexBuffer = this._vertexBuffers[key];
  38526. vertexBuffer._rebuild();
  38527. }
  38528. };
  38529. /**
  38530. * Affects all gemetry data in one call
  38531. * @param vertexData defines the geometry data
  38532. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38533. */
  38534. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38535. vertexData.applyToGeometry(this, updatable);
  38536. this.notifyUpdate();
  38537. };
  38538. /**
  38539. * Set specific vertex data
  38540. * @param kind defines the data kind (Position, normal, etc...)
  38541. * @param data defines the vertex data to use
  38542. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38543. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38544. */
  38545. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38546. if (updatable === void 0) { updatable = false; }
  38547. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38548. this.setVerticesBuffer(buffer);
  38549. };
  38550. /**
  38551. * Removes a specific vertex data
  38552. * @param kind defines the data kind (Position, normal, etc...)
  38553. */
  38554. Geometry.prototype.removeVerticesData = function (kind) {
  38555. if (this._vertexBuffers[kind]) {
  38556. this._vertexBuffers[kind].dispose();
  38557. delete this._vertexBuffers[kind];
  38558. }
  38559. };
  38560. /**
  38561. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38562. * @param buffer defines the vertex buffer to use
  38563. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38564. */
  38565. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38566. if (totalVertices === void 0) { totalVertices = null; }
  38567. var kind = buffer.getKind();
  38568. if (this._vertexBuffers[kind]) {
  38569. this._vertexBuffers[kind].dispose();
  38570. }
  38571. this._vertexBuffers[kind] = buffer;
  38572. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38573. var data = buffer.getData();
  38574. if (totalVertices != null) {
  38575. this._totalVertices = totalVertices;
  38576. }
  38577. else {
  38578. if (data != null) {
  38579. this._totalVertices = data.length / (buffer.byteStride / 4);
  38580. }
  38581. }
  38582. this._updateExtend(data);
  38583. this._resetPointsArrayCache();
  38584. var meshes = this._meshes;
  38585. var numOfMeshes = meshes.length;
  38586. for (var index = 0; index < numOfMeshes; index++) {
  38587. var mesh = meshes[index];
  38588. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38589. mesh._createGlobalSubMesh(false);
  38590. mesh.computeWorldMatrix(true);
  38591. }
  38592. }
  38593. this.notifyUpdate(kind);
  38594. if (this._vertexArrayObjects) {
  38595. this._disposeVertexArrayObjects();
  38596. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38597. }
  38598. };
  38599. /**
  38600. * Update a specific vertex buffer
  38601. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38602. * It will do nothing if the buffer is not updatable
  38603. * @param kind defines the data kind (Position, normal, etc...)
  38604. * @param data defines the data to use
  38605. * @param offset defines the offset in the target buffer where to store the data
  38606. * @param useBytes set to true if the offset is in bytes
  38607. */
  38608. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38609. if (useBytes === void 0) { useBytes = false; }
  38610. var vertexBuffer = this.getVertexBuffer(kind);
  38611. if (!vertexBuffer) {
  38612. return;
  38613. }
  38614. vertexBuffer.updateDirectly(data, offset, useBytes);
  38615. this.notifyUpdate(kind);
  38616. };
  38617. /**
  38618. * Update a specific vertex buffer
  38619. * This function will create a new buffer if the current one is not updatable
  38620. * @param kind defines the data kind (Position, normal, etc...)
  38621. * @param data defines the data to use
  38622. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38623. */
  38624. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38625. if (updateExtends === void 0) { updateExtends = false; }
  38626. var vertexBuffer = this.getVertexBuffer(kind);
  38627. if (!vertexBuffer) {
  38628. return;
  38629. }
  38630. vertexBuffer.update(data);
  38631. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38632. this._updateBoundingInfo(updateExtends, data);
  38633. }
  38634. this.notifyUpdate(kind);
  38635. };
  38636. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38637. if (updateExtends) {
  38638. this._updateExtend(data);
  38639. }
  38640. var meshes = this._meshes;
  38641. var numOfMeshes = meshes.length;
  38642. this._resetPointsArrayCache();
  38643. for (var index = 0; index < numOfMeshes; index++) {
  38644. var mesh = meshes[index];
  38645. if (updateExtends) {
  38646. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38647. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38648. var subMesh = mesh.subMeshes[subIndex];
  38649. subMesh.refreshBoundingInfo();
  38650. }
  38651. }
  38652. }
  38653. };
  38654. /** @hidden */
  38655. Geometry.prototype._bind = function (effect, indexToBind) {
  38656. if (!effect) {
  38657. return;
  38658. }
  38659. if (indexToBind === undefined) {
  38660. indexToBind = this._indexBuffer;
  38661. }
  38662. var vbs = this.getVertexBuffers();
  38663. if (!vbs) {
  38664. return;
  38665. }
  38666. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38667. this._engine.bindBuffers(vbs, indexToBind, effect);
  38668. return;
  38669. }
  38670. // Using VAO
  38671. if (!this._vertexArrayObjects[effect.key]) {
  38672. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38673. }
  38674. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38675. };
  38676. /**
  38677. * Gets total number of vertices
  38678. * @returns the total number of vertices
  38679. */
  38680. Geometry.prototype.getTotalVertices = function () {
  38681. if (!this.isReady()) {
  38682. return 0;
  38683. }
  38684. return this._totalVertices;
  38685. };
  38686. /**
  38687. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38688. * @param kind defines the data kind (Position, normal, etc...)
  38689. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38690. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38691. * @returns a float array containing vertex data
  38692. */
  38693. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38694. var vertexBuffer = this.getVertexBuffer(kind);
  38695. if (!vertexBuffer) {
  38696. return null;
  38697. }
  38698. var data = vertexBuffer.getData();
  38699. if (!data) {
  38700. return null;
  38701. }
  38702. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38703. var count = this._totalVertices * vertexBuffer.getSize();
  38704. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38705. var copy_1 = new Array(count);
  38706. vertexBuffer.forEach(count, function (value, index) {
  38707. copy_1[index] = value;
  38708. });
  38709. return copy_1;
  38710. }
  38711. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38712. if (data instanceof Array) {
  38713. var offset = vertexBuffer.byteOffset / 4;
  38714. return BABYLON.Tools.Slice(data, offset, offset + count);
  38715. }
  38716. else if (data instanceof ArrayBuffer) {
  38717. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38718. }
  38719. else {
  38720. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38721. }
  38722. }
  38723. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38724. return BABYLON.Tools.Slice(data);
  38725. }
  38726. return data;
  38727. };
  38728. /**
  38729. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38730. * @param kind defines the data kind (Position, normal, etc...)
  38731. * @returns true if the vertex buffer with the specified kind is updatable
  38732. */
  38733. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38734. var vb = this._vertexBuffers[kind];
  38735. if (!vb) {
  38736. return false;
  38737. }
  38738. return vb.isUpdatable();
  38739. };
  38740. /**
  38741. * Gets a specific vertex buffer
  38742. * @param kind defines the data kind (Position, normal, etc...)
  38743. * @returns a {BABYLON.VertexBuffer}
  38744. */
  38745. Geometry.prototype.getVertexBuffer = function (kind) {
  38746. if (!this.isReady()) {
  38747. return null;
  38748. }
  38749. return this._vertexBuffers[kind];
  38750. };
  38751. /**
  38752. * Returns all vertex buffers
  38753. * @return an object holding all vertex buffers indexed by kind
  38754. */
  38755. Geometry.prototype.getVertexBuffers = function () {
  38756. if (!this.isReady()) {
  38757. return null;
  38758. }
  38759. return this._vertexBuffers;
  38760. };
  38761. /**
  38762. * Gets a boolean indicating if specific vertex buffer is present
  38763. * @param kind defines the data kind (Position, normal, etc...)
  38764. * @returns true if data is present
  38765. */
  38766. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38767. if (!this._vertexBuffers) {
  38768. if (this._delayInfo) {
  38769. return this._delayInfo.indexOf(kind) !== -1;
  38770. }
  38771. return false;
  38772. }
  38773. return this._vertexBuffers[kind] !== undefined;
  38774. };
  38775. /**
  38776. * Gets a list of all attached data kinds (Position, normal, etc...)
  38777. * @returns a list of string containing all kinds
  38778. */
  38779. Geometry.prototype.getVerticesDataKinds = function () {
  38780. var result = [];
  38781. var kind;
  38782. if (!this._vertexBuffers && this._delayInfo) {
  38783. for (kind in this._delayInfo) {
  38784. result.push(kind);
  38785. }
  38786. }
  38787. else {
  38788. for (kind in this._vertexBuffers) {
  38789. result.push(kind);
  38790. }
  38791. }
  38792. return result;
  38793. };
  38794. /**
  38795. * Update index buffer
  38796. * @param indices defines the indices to store in the index buffer
  38797. * @param offset defines the offset in the target buffer where to store the data
  38798. */
  38799. Geometry.prototype.updateIndices = function (indices, offset) {
  38800. if (!this._indexBuffer) {
  38801. return;
  38802. }
  38803. if (!this._indexBufferIsUpdatable) {
  38804. this.setIndices(indices, null, true);
  38805. }
  38806. else {
  38807. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38808. }
  38809. };
  38810. /**
  38811. * Creates a new index buffer
  38812. * @param indices defines the indices to store in the index buffer
  38813. * @param totalVertices defines the total number of vertices (could be null)
  38814. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38815. */
  38816. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38817. if (totalVertices === void 0) { totalVertices = null; }
  38818. if (updatable === void 0) { updatable = false; }
  38819. if (this._indexBuffer) {
  38820. this._engine._releaseBuffer(this._indexBuffer);
  38821. }
  38822. this._disposeVertexArrayObjects();
  38823. this._indices = indices;
  38824. this._indexBufferIsUpdatable = updatable;
  38825. if (this._meshes.length !== 0 && this._indices) {
  38826. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38827. }
  38828. if (totalVertices != undefined) { // including null and undefined
  38829. this._totalVertices = totalVertices;
  38830. }
  38831. var meshes = this._meshes;
  38832. var numOfMeshes = meshes.length;
  38833. for (var index = 0; index < numOfMeshes; index++) {
  38834. meshes[index]._createGlobalSubMesh(true);
  38835. }
  38836. this.notifyUpdate();
  38837. };
  38838. /**
  38839. * Return the total number of indices
  38840. * @returns the total number of indices
  38841. */
  38842. Geometry.prototype.getTotalIndices = function () {
  38843. if (!this.isReady()) {
  38844. return 0;
  38845. }
  38846. return this._indices.length;
  38847. };
  38848. /**
  38849. * Gets the index buffer array
  38850. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38851. * @returns the index buffer array
  38852. */
  38853. Geometry.prototype.getIndices = function (copyWhenShared) {
  38854. if (!this.isReady()) {
  38855. return null;
  38856. }
  38857. var orig = this._indices;
  38858. if (!copyWhenShared || this._meshes.length === 1) {
  38859. return orig;
  38860. }
  38861. else {
  38862. var len = orig.length;
  38863. var copy = [];
  38864. for (var i = 0; i < len; i++) {
  38865. copy.push(orig[i]);
  38866. }
  38867. return copy;
  38868. }
  38869. };
  38870. /**
  38871. * Gets the index buffer
  38872. * @return the index buffer
  38873. */
  38874. Geometry.prototype.getIndexBuffer = function () {
  38875. if (!this.isReady()) {
  38876. return null;
  38877. }
  38878. return this._indexBuffer;
  38879. };
  38880. /** @hidden */
  38881. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38882. if (effect === void 0) { effect = null; }
  38883. if (!effect || !this._vertexArrayObjects) {
  38884. return;
  38885. }
  38886. if (this._vertexArrayObjects[effect.key]) {
  38887. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38888. delete this._vertexArrayObjects[effect.key];
  38889. }
  38890. };
  38891. /**
  38892. * Release the associated resources for a specific mesh
  38893. * @param mesh defines the source mesh
  38894. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38895. */
  38896. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38897. var meshes = this._meshes;
  38898. var index = meshes.indexOf(mesh);
  38899. if (index === -1) {
  38900. return;
  38901. }
  38902. meshes.splice(index, 1);
  38903. mesh._geometry = null;
  38904. if (meshes.length === 0 && shouldDispose) {
  38905. this.dispose();
  38906. }
  38907. };
  38908. /**
  38909. * Apply current geometry to a given mesh
  38910. * @param mesh defines the mesh to apply geometry to
  38911. */
  38912. Geometry.prototype.applyToMesh = function (mesh) {
  38913. if (mesh._geometry === this) {
  38914. return;
  38915. }
  38916. var previousGeometry = mesh._geometry;
  38917. if (previousGeometry) {
  38918. previousGeometry.releaseForMesh(mesh);
  38919. }
  38920. var meshes = this._meshes;
  38921. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38922. mesh._geometry = this;
  38923. this._scene.pushGeometry(this);
  38924. meshes.push(mesh);
  38925. if (this.isReady()) {
  38926. this._applyToMesh(mesh);
  38927. }
  38928. else {
  38929. mesh._boundingInfo = this._boundingInfo;
  38930. }
  38931. };
  38932. Geometry.prototype._updateExtend = function (data) {
  38933. if (data === void 0) { data = null; }
  38934. if (!data) {
  38935. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38936. }
  38937. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38938. };
  38939. Geometry.prototype._applyToMesh = function (mesh) {
  38940. var numOfMeshes = this._meshes.length;
  38941. // vertexBuffers
  38942. for (var kind in this._vertexBuffers) {
  38943. if (numOfMeshes === 1) {
  38944. this._vertexBuffers[kind].create();
  38945. }
  38946. var buffer = this._vertexBuffers[kind].getBuffer();
  38947. if (buffer)
  38948. buffer.references = numOfMeshes;
  38949. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38950. if (!this._extend) {
  38951. this._updateExtend();
  38952. }
  38953. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38954. mesh._createGlobalSubMesh(false);
  38955. //bounding info was just created again, world matrix should be applied again.
  38956. mesh._updateBoundingInfo();
  38957. }
  38958. }
  38959. // indexBuffer
  38960. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38961. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38962. }
  38963. if (this._indexBuffer) {
  38964. this._indexBuffer.references = numOfMeshes;
  38965. }
  38966. };
  38967. Geometry.prototype.notifyUpdate = function (kind) {
  38968. if (this.onGeometryUpdated) {
  38969. this.onGeometryUpdated(this, kind);
  38970. }
  38971. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38972. var mesh = _a[_i];
  38973. mesh._markSubMeshesAsAttributesDirty();
  38974. }
  38975. };
  38976. /**
  38977. * Load the geometry if it was flagged as delay loaded
  38978. * @param scene defines the hosting scene
  38979. * @param onLoaded defines a callback called when the geometry is loaded
  38980. */
  38981. Geometry.prototype.load = function (scene, onLoaded) {
  38982. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38983. return;
  38984. }
  38985. if (this.isReady()) {
  38986. if (onLoaded) {
  38987. onLoaded();
  38988. }
  38989. return;
  38990. }
  38991. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38992. this._queueLoad(scene, onLoaded);
  38993. };
  38994. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38995. var _this = this;
  38996. if (!this.delayLoadingFile) {
  38997. return;
  38998. }
  38999. scene._addPendingData(this);
  39000. scene._loadFile(this.delayLoadingFile, function (data) {
  39001. if (!_this._delayLoadingFunction) {
  39002. return;
  39003. }
  39004. _this._delayLoadingFunction(JSON.parse(data), _this);
  39005. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39006. _this._delayInfo = [];
  39007. scene._removePendingData(_this);
  39008. var meshes = _this._meshes;
  39009. var numOfMeshes = meshes.length;
  39010. for (var index = 0; index < numOfMeshes; index++) {
  39011. _this._applyToMesh(meshes[index]);
  39012. }
  39013. if (onLoaded) {
  39014. onLoaded();
  39015. }
  39016. }, undefined, true);
  39017. };
  39018. /**
  39019. * Invert the geometry to move from a right handed system to a left handed one.
  39020. */
  39021. Geometry.prototype.toLeftHanded = function () {
  39022. // Flip faces
  39023. var tIndices = this.getIndices(false);
  39024. if (tIndices != null && tIndices.length > 0) {
  39025. for (var i = 0; i < tIndices.length; i += 3) {
  39026. var tTemp = tIndices[i + 0];
  39027. tIndices[i + 0] = tIndices[i + 2];
  39028. tIndices[i + 2] = tTemp;
  39029. }
  39030. this.setIndices(tIndices);
  39031. }
  39032. // Negate position.z
  39033. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39034. if (tPositions != null && tPositions.length > 0) {
  39035. for (var i = 0; i < tPositions.length; i += 3) {
  39036. tPositions[i + 2] = -tPositions[i + 2];
  39037. }
  39038. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39039. }
  39040. // Negate normal.z
  39041. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39042. if (tNormals != null && tNormals.length > 0) {
  39043. for (var i = 0; i < tNormals.length; i += 3) {
  39044. tNormals[i + 2] = -tNormals[i + 2];
  39045. }
  39046. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39047. }
  39048. };
  39049. // Cache
  39050. /** @hidden */
  39051. Geometry.prototype._resetPointsArrayCache = function () {
  39052. this._positions = null;
  39053. };
  39054. /** @hidden */
  39055. Geometry.prototype._generatePointsArray = function () {
  39056. if (this._positions)
  39057. return true;
  39058. this._positions = [];
  39059. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39060. if (!data) {
  39061. return false;
  39062. }
  39063. for (var index = 0; index < data.length; index += 3) {
  39064. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39065. }
  39066. return true;
  39067. };
  39068. /**
  39069. * Gets a value indicating if the geometry is disposed
  39070. * @returns true if the geometry was disposed
  39071. */
  39072. Geometry.prototype.isDisposed = function () {
  39073. return this._isDisposed;
  39074. };
  39075. Geometry.prototype._disposeVertexArrayObjects = function () {
  39076. if (this._vertexArrayObjects) {
  39077. for (var kind in this._vertexArrayObjects) {
  39078. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39079. }
  39080. this._vertexArrayObjects = {};
  39081. }
  39082. };
  39083. /**
  39084. * Free all associated resources
  39085. */
  39086. Geometry.prototype.dispose = function () {
  39087. var meshes = this._meshes;
  39088. var numOfMeshes = meshes.length;
  39089. var index;
  39090. for (index = 0; index < numOfMeshes; index++) {
  39091. this.releaseForMesh(meshes[index]);
  39092. }
  39093. this._meshes = [];
  39094. this._disposeVertexArrayObjects();
  39095. for (var kind in this._vertexBuffers) {
  39096. this._vertexBuffers[kind].dispose();
  39097. }
  39098. this._vertexBuffers = {};
  39099. this._totalVertices = 0;
  39100. if (this._indexBuffer) {
  39101. this._engine._releaseBuffer(this._indexBuffer);
  39102. }
  39103. this._indexBuffer = null;
  39104. this._indices = [];
  39105. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39106. this.delayLoadingFile = null;
  39107. this._delayLoadingFunction = null;
  39108. this._delayInfo = [];
  39109. this._boundingInfo = null;
  39110. this._scene.removeGeometry(this);
  39111. this._isDisposed = true;
  39112. };
  39113. /**
  39114. * Clone the current geometry into a new geometry
  39115. * @param id defines the unique ID of the new geometry
  39116. * @returns a new geometry object
  39117. */
  39118. Geometry.prototype.copy = function (id) {
  39119. var vertexData = new BABYLON.VertexData();
  39120. vertexData.indices = [];
  39121. var indices = this.getIndices();
  39122. if (indices) {
  39123. for (var index = 0; index < indices.length; index++) {
  39124. vertexData.indices.push(indices[index]);
  39125. }
  39126. }
  39127. var updatable = false;
  39128. var stopChecking = false;
  39129. var kind;
  39130. for (kind in this._vertexBuffers) {
  39131. // using slice() to make a copy of the array and not just reference it
  39132. var data = this.getVerticesData(kind);
  39133. if (data instanceof Float32Array) {
  39134. vertexData.set(new Float32Array(data), kind);
  39135. }
  39136. else {
  39137. vertexData.set(data.slice(0), kind);
  39138. }
  39139. if (!stopChecking) {
  39140. var vb = this.getVertexBuffer(kind);
  39141. if (vb) {
  39142. updatable = vb.isUpdatable();
  39143. stopChecking = !updatable;
  39144. }
  39145. }
  39146. }
  39147. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39148. geometry.delayLoadState = this.delayLoadState;
  39149. geometry.delayLoadingFile = this.delayLoadingFile;
  39150. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39151. for (kind in this._delayInfo) {
  39152. geometry._delayInfo = geometry._delayInfo || [];
  39153. geometry._delayInfo.push(kind);
  39154. }
  39155. // Bounding info
  39156. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39157. return geometry;
  39158. };
  39159. /**
  39160. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39161. * @return a JSON representation of the current geometry data (without the vertices data)
  39162. */
  39163. Geometry.prototype.serialize = function () {
  39164. var serializationObject = {};
  39165. serializationObject.id = this.id;
  39166. serializationObject.updatable = this._updatable;
  39167. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39168. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39169. }
  39170. return serializationObject;
  39171. };
  39172. Geometry.prototype.toNumberArray = function (origin) {
  39173. if (Array.isArray(origin)) {
  39174. return origin;
  39175. }
  39176. else {
  39177. return Array.prototype.slice.call(origin);
  39178. }
  39179. };
  39180. /**
  39181. * Serialize all vertices data into a JSON oject
  39182. * @returns a JSON representation of the current geometry data
  39183. */
  39184. Geometry.prototype.serializeVerticeData = function () {
  39185. var serializationObject = this.serialize();
  39186. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39187. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39188. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39189. serializationObject.positions._updatable = true;
  39190. }
  39191. }
  39192. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39193. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39194. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39195. serializationObject.normals._updatable = true;
  39196. }
  39197. }
  39198. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39199. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39200. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39201. serializationObject.tangets._updatable = true;
  39202. }
  39203. }
  39204. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39205. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39206. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39207. serializationObject.uvs._updatable = true;
  39208. }
  39209. }
  39210. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39211. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39212. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39213. serializationObject.uv2s._updatable = true;
  39214. }
  39215. }
  39216. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39217. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39218. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39219. serializationObject.uv3s._updatable = true;
  39220. }
  39221. }
  39222. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39223. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39224. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39225. serializationObject.uv4s._updatable = true;
  39226. }
  39227. }
  39228. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39229. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39230. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39231. serializationObject.uv5s._updatable = true;
  39232. }
  39233. }
  39234. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39235. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39236. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39237. serializationObject.uv6s._updatable = true;
  39238. }
  39239. }
  39240. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39241. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39242. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39243. serializationObject.colors._updatable = true;
  39244. }
  39245. }
  39246. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39247. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39248. serializationObject.matricesIndices._isExpanded = true;
  39249. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39250. serializationObject.matricesIndices._updatable = true;
  39251. }
  39252. }
  39253. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39254. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39255. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39256. serializationObject.matricesWeights._updatable = true;
  39257. }
  39258. }
  39259. serializationObject.indices = this.toNumberArray(this.getIndices());
  39260. return serializationObject;
  39261. };
  39262. // Statics
  39263. /**
  39264. * Extracts a clone of a mesh geometry
  39265. * @param mesh defines the source mesh
  39266. * @param id defines the unique ID of the new geometry object
  39267. * @returns the new geometry object
  39268. */
  39269. Geometry.ExtractFromMesh = function (mesh, id) {
  39270. var geometry = mesh._geometry;
  39271. if (!geometry) {
  39272. return null;
  39273. }
  39274. return geometry.copy(id);
  39275. };
  39276. /**
  39277. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39278. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39279. * Be aware Math.random() could cause collisions, but:
  39280. * "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"
  39281. * @returns a string containing a new GUID
  39282. */
  39283. Geometry.RandomId = function () {
  39284. return BABYLON.Tools.RandomId();
  39285. };
  39286. /** @hidden */
  39287. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39288. var scene = mesh.getScene();
  39289. // Geometry
  39290. var geometryId = parsedGeometry.geometryId;
  39291. if (geometryId) {
  39292. var geometry = scene.getGeometryByID(geometryId);
  39293. if (geometry) {
  39294. geometry.applyToMesh(mesh);
  39295. }
  39296. }
  39297. else if (parsedGeometry instanceof ArrayBuffer) {
  39298. var binaryInfo = mesh._binaryInfo;
  39299. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39300. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39301. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39302. }
  39303. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39304. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39305. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39306. }
  39307. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39308. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39309. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39310. }
  39311. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39312. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39313. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39314. }
  39315. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39316. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39317. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39318. }
  39319. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39320. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39321. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39322. }
  39323. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39324. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39325. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39326. }
  39327. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39328. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39329. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39330. }
  39331. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39332. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39333. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39334. }
  39335. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39336. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39337. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39338. }
  39339. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39340. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39341. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39342. }
  39343. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39344. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39345. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39346. }
  39347. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39348. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39349. mesh.setIndices(indicesData, null);
  39350. }
  39351. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39352. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39353. mesh.subMeshes = [];
  39354. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39355. var materialIndex = subMeshesData[(i * 5) + 0];
  39356. var verticesStart = subMeshesData[(i * 5) + 1];
  39357. var verticesCount = subMeshesData[(i * 5) + 2];
  39358. var indexStart = subMeshesData[(i * 5) + 3];
  39359. var indexCount = subMeshesData[(i * 5) + 4];
  39360. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39361. }
  39362. }
  39363. }
  39364. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39365. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39366. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39367. if (parsedGeometry.tangents) {
  39368. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39369. }
  39370. if (parsedGeometry.uvs) {
  39371. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39372. }
  39373. if (parsedGeometry.uvs2) {
  39374. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39375. }
  39376. if (parsedGeometry.uvs3) {
  39377. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39378. }
  39379. if (parsedGeometry.uvs4) {
  39380. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39381. }
  39382. if (parsedGeometry.uvs5) {
  39383. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39384. }
  39385. if (parsedGeometry.uvs6) {
  39386. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39387. }
  39388. if (parsedGeometry.colors) {
  39389. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39390. }
  39391. if (parsedGeometry.matricesIndices) {
  39392. if (!parsedGeometry.matricesIndices._isExpanded) {
  39393. var floatIndices = [];
  39394. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39395. var matricesIndex = parsedGeometry.matricesIndices[i];
  39396. floatIndices.push(matricesIndex & 0x000000FF);
  39397. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39398. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39399. floatIndices.push(matricesIndex >> 24);
  39400. }
  39401. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39402. }
  39403. else {
  39404. delete parsedGeometry.matricesIndices._isExpanded;
  39405. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39406. }
  39407. }
  39408. if (parsedGeometry.matricesIndicesExtra) {
  39409. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39410. var floatIndices = [];
  39411. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39412. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39413. floatIndices.push(matricesIndex & 0x000000FF);
  39414. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39415. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39416. floatIndices.push(matricesIndex >> 24);
  39417. }
  39418. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39419. }
  39420. else {
  39421. delete parsedGeometry.matricesIndices._isExpanded;
  39422. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39423. }
  39424. }
  39425. if (parsedGeometry.matricesWeights) {
  39426. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39427. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39428. }
  39429. if (parsedGeometry.matricesWeightsExtra) {
  39430. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39431. }
  39432. mesh.setIndices(parsedGeometry.indices, null);
  39433. }
  39434. // SubMeshes
  39435. if (parsedGeometry.subMeshes) {
  39436. mesh.subMeshes = [];
  39437. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39438. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39439. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39440. }
  39441. }
  39442. // Flat shading
  39443. if (mesh._shouldGenerateFlatShading) {
  39444. mesh.convertToFlatShadedMesh();
  39445. delete mesh._shouldGenerateFlatShading;
  39446. }
  39447. // Update
  39448. mesh.computeWorldMatrix(true);
  39449. // Octree
  39450. var sceneOctree = scene.selectionOctree;
  39451. if (sceneOctree !== undefined && sceneOctree !== null) {
  39452. sceneOctree.addMesh(mesh);
  39453. }
  39454. };
  39455. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39456. var epsilon = 1e-3;
  39457. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39458. return;
  39459. }
  39460. var noInfluenceBoneIndex = 0.0;
  39461. if (parsedGeometry.skeletonId > -1) {
  39462. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39463. if (!skeleton) {
  39464. return;
  39465. }
  39466. noInfluenceBoneIndex = skeleton.bones.length;
  39467. }
  39468. else {
  39469. return;
  39470. }
  39471. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39472. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39473. var matricesWeights = parsedGeometry.matricesWeights;
  39474. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39475. var influencers = parsedGeometry.numBoneInfluencer;
  39476. var size = matricesWeights.length;
  39477. for (var i = 0; i < size; i += 4) {
  39478. var weight = 0.0;
  39479. var firstZeroWeight = -1;
  39480. for (var j = 0; j < 4; j++) {
  39481. var w = matricesWeights[i + j];
  39482. weight += w;
  39483. if (w < epsilon && firstZeroWeight < 0) {
  39484. firstZeroWeight = j;
  39485. }
  39486. }
  39487. if (matricesWeightsExtra) {
  39488. for (var j = 0; j < 4; j++) {
  39489. var w = matricesWeightsExtra[i + j];
  39490. weight += w;
  39491. if (w < epsilon && firstZeroWeight < 0) {
  39492. firstZeroWeight = j + 4;
  39493. }
  39494. }
  39495. }
  39496. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39497. firstZeroWeight = influencers - 1;
  39498. }
  39499. if (weight > epsilon) {
  39500. var mweight = 1.0 / weight;
  39501. for (var j = 0; j < 4; j++) {
  39502. matricesWeights[i + j] *= mweight;
  39503. }
  39504. if (matricesWeightsExtra) {
  39505. for (var j = 0; j < 4; j++) {
  39506. matricesWeightsExtra[i + j] *= mweight;
  39507. }
  39508. }
  39509. }
  39510. else {
  39511. if (firstZeroWeight >= 4) {
  39512. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39513. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39514. }
  39515. else {
  39516. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39517. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39518. }
  39519. }
  39520. }
  39521. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39522. if (parsedGeometry.matricesWeightsExtra) {
  39523. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39524. }
  39525. };
  39526. /**
  39527. * Create a new geometry from persisted data (Using .babylon file format)
  39528. * @param parsedVertexData defines the persisted data
  39529. * @param scene defines the hosting scene
  39530. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39531. * @returns the new geometry object
  39532. */
  39533. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39534. if (scene.getGeometryByID(parsedVertexData.id)) {
  39535. return null; // null since geometry could be something else than a box...
  39536. }
  39537. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39538. if (BABYLON.Tags) {
  39539. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39540. }
  39541. if (parsedVertexData.delayLoadingFile) {
  39542. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39543. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39544. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39545. geometry._delayInfo = [];
  39546. if (parsedVertexData.hasUVs) {
  39547. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39548. }
  39549. if (parsedVertexData.hasUVs2) {
  39550. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39551. }
  39552. if (parsedVertexData.hasUVs3) {
  39553. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39554. }
  39555. if (parsedVertexData.hasUVs4) {
  39556. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39557. }
  39558. if (parsedVertexData.hasUVs5) {
  39559. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39560. }
  39561. if (parsedVertexData.hasUVs6) {
  39562. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39563. }
  39564. if (parsedVertexData.hasColors) {
  39565. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39566. }
  39567. if (parsedVertexData.hasMatricesIndices) {
  39568. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39569. }
  39570. if (parsedVertexData.hasMatricesWeights) {
  39571. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39572. }
  39573. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39574. }
  39575. else {
  39576. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39577. }
  39578. scene.pushGeometry(geometry, true);
  39579. return geometry;
  39580. };
  39581. return Geometry;
  39582. }());
  39583. BABYLON.Geometry = Geometry;
  39584. // Primitives
  39585. /// Abstract class
  39586. /**
  39587. * Abstract class used to provide common services for all typed geometries
  39588. * @hidden
  39589. */
  39590. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39591. __extends(_PrimitiveGeometry, _super);
  39592. /**
  39593. * Creates a new typed geometry
  39594. * @param id defines the unique ID of the geometry
  39595. * @param scene defines the hosting scene
  39596. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39597. * @param mesh defines the hosting mesh (can be null)
  39598. */
  39599. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39600. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39601. if (mesh === void 0) { mesh = null; }
  39602. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39603. _this._canBeRegenerated = _canBeRegenerated;
  39604. _this._beingRegenerated = true;
  39605. _this.regenerate();
  39606. _this._beingRegenerated = false;
  39607. return _this;
  39608. }
  39609. /**
  39610. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39611. * @returns true if the geometry can be regenerated
  39612. */
  39613. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39614. return this._canBeRegenerated;
  39615. };
  39616. /**
  39617. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39618. */
  39619. _PrimitiveGeometry.prototype.regenerate = function () {
  39620. if (!this._canBeRegenerated) {
  39621. return;
  39622. }
  39623. this._beingRegenerated = true;
  39624. this.setAllVerticesData(this._regenerateVertexData(), false);
  39625. this._beingRegenerated = false;
  39626. };
  39627. /**
  39628. * Clone the geometry
  39629. * @param id defines the unique ID of the new geometry
  39630. * @returns the new geometry
  39631. */
  39632. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39633. return _super.prototype.copy.call(this, id);
  39634. };
  39635. // overrides
  39636. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39637. if (!this._beingRegenerated) {
  39638. return;
  39639. }
  39640. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39641. };
  39642. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39643. if (!this._beingRegenerated) {
  39644. return;
  39645. }
  39646. _super.prototype.setVerticesData.call(this, kind, data, false);
  39647. };
  39648. // to override
  39649. /** @hidden */
  39650. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39651. throw new Error("Abstract method");
  39652. };
  39653. _PrimitiveGeometry.prototype.copy = function (id) {
  39654. throw new Error("Must be overriden in sub-classes.");
  39655. };
  39656. _PrimitiveGeometry.prototype.serialize = function () {
  39657. var serializationObject = _super.prototype.serialize.call(this);
  39658. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39659. return serializationObject;
  39660. };
  39661. return _PrimitiveGeometry;
  39662. }(Geometry));
  39663. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39664. /**
  39665. * Creates a ribbon geometry
  39666. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39667. */
  39668. var RibbonGeometry = /** @class */ (function (_super) {
  39669. __extends(RibbonGeometry, _super);
  39670. /**
  39671. * Creates a ribbon geometry
  39672. * @param id defines the unique ID of the geometry
  39673. * @param scene defines the hosting scene
  39674. * @param pathArray defines the array of paths to use
  39675. * @param closeArray defines if the last path and the first path must be joined
  39676. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39677. * @param offset defines the offset between points
  39678. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39679. * @param mesh defines the hosting mesh (can be null)
  39680. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39681. */
  39682. function RibbonGeometry(id, scene,
  39683. /**
  39684. * Defines the array of paths to use
  39685. */
  39686. pathArray,
  39687. /**
  39688. * Defines if the last and first points of each path in your pathArray must be joined
  39689. */
  39690. closeArray,
  39691. /**
  39692. * Defines if the last and first points of each path in your pathArray must be joined
  39693. */
  39694. closePath,
  39695. /**
  39696. * Defines the offset between points
  39697. */
  39698. offset, canBeRegenerated, mesh,
  39699. /**
  39700. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39701. */
  39702. side) {
  39703. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39704. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39705. _this.pathArray = pathArray;
  39706. _this.closeArray = closeArray;
  39707. _this.closePath = closePath;
  39708. _this.offset = offset;
  39709. _this.side = side;
  39710. return _this;
  39711. }
  39712. /** @hidden */
  39713. RibbonGeometry.prototype._regenerateVertexData = function () {
  39714. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39715. };
  39716. RibbonGeometry.prototype.copy = function (id) {
  39717. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39718. };
  39719. return RibbonGeometry;
  39720. }(_PrimitiveGeometry));
  39721. BABYLON.RibbonGeometry = RibbonGeometry;
  39722. /**
  39723. * Creates a box geometry
  39724. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39725. */
  39726. var BoxGeometry = /** @class */ (function (_super) {
  39727. __extends(BoxGeometry, _super);
  39728. /**
  39729. * Creates a box geometry
  39730. * @param id defines the unique ID of the geometry
  39731. * @param scene defines the hosting scene
  39732. * @param size defines the zise of the box (width, height and depth are the same)
  39733. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39734. * @param mesh defines the hosting mesh (can be null)
  39735. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39736. */
  39737. function BoxGeometry(id, scene,
  39738. /**
  39739. * Defines the zise of the box (width, height and depth are the same)
  39740. */
  39741. size, canBeRegenerated, mesh,
  39742. /**
  39743. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39744. */
  39745. side) {
  39746. if (mesh === void 0) { mesh = null; }
  39747. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39748. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39749. _this.size = size;
  39750. _this.side = side;
  39751. return _this;
  39752. }
  39753. BoxGeometry.prototype._regenerateVertexData = function () {
  39754. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39755. };
  39756. BoxGeometry.prototype.copy = function (id) {
  39757. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39758. };
  39759. BoxGeometry.prototype.serialize = function () {
  39760. var serializationObject = _super.prototype.serialize.call(this);
  39761. serializationObject.size = this.size;
  39762. return serializationObject;
  39763. };
  39764. BoxGeometry.Parse = function (parsedBox, scene) {
  39765. if (scene.getGeometryByID(parsedBox.id)) {
  39766. return null; // null since geometry could be something else than a box...
  39767. }
  39768. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39769. if (BABYLON.Tags) {
  39770. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39771. }
  39772. scene.pushGeometry(box, true);
  39773. return box;
  39774. };
  39775. return BoxGeometry;
  39776. }(_PrimitiveGeometry));
  39777. BABYLON.BoxGeometry = BoxGeometry;
  39778. /**
  39779. * Creates a sphere geometry
  39780. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39781. */
  39782. var SphereGeometry = /** @class */ (function (_super) {
  39783. __extends(SphereGeometry, _super);
  39784. /**
  39785. * Create a new sphere geometry
  39786. * @param id defines the unique ID of the geometry
  39787. * @param scene defines the hosting scene
  39788. * @param segments defines the number of segments to use to create the sphere
  39789. * @param diameter defines the diameter of the sphere
  39790. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39791. * @param mesh defines the hosting mesh (can be null)
  39792. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39793. */
  39794. function SphereGeometry(id, scene,
  39795. /**
  39796. * Defines the number of segments to use to create the sphere
  39797. */
  39798. segments,
  39799. /**
  39800. * Defines the diameter of the sphere
  39801. */
  39802. diameter, canBeRegenerated, mesh,
  39803. /**
  39804. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39805. */
  39806. side) {
  39807. if (mesh === void 0) { mesh = null; }
  39808. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39809. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39810. _this.segments = segments;
  39811. _this.diameter = diameter;
  39812. _this.side = side;
  39813. return _this;
  39814. }
  39815. SphereGeometry.prototype._regenerateVertexData = function () {
  39816. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39817. };
  39818. SphereGeometry.prototype.copy = function (id) {
  39819. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39820. };
  39821. SphereGeometry.prototype.serialize = function () {
  39822. var serializationObject = _super.prototype.serialize.call(this);
  39823. serializationObject.segments = this.segments;
  39824. serializationObject.diameter = this.diameter;
  39825. return serializationObject;
  39826. };
  39827. SphereGeometry.Parse = function (parsedSphere, scene) {
  39828. if (scene.getGeometryByID(parsedSphere.id)) {
  39829. return null; // null since geometry could be something else than a sphere...
  39830. }
  39831. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39832. if (BABYLON.Tags) {
  39833. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39834. }
  39835. scene.pushGeometry(sphere, true);
  39836. return sphere;
  39837. };
  39838. return SphereGeometry;
  39839. }(_PrimitiveGeometry));
  39840. BABYLON.SphereGeometry = SphereGeometry;
  39841. /**
  39842. * Creates a disc geometry
  39843. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39844. */
  39845. var DiscGeometry = /** @class */ (function (_super) {
  39846. __extends(DiscGeometry, _super);
  39847. /**
  39848. * Creates a new disc geometry
  39849. * @param id defines the unique ID of the geometry
  39850. * @param scene defines the hosting scene
  39851. * @param radius defines the radius of the disc
  39852. * @param tessellation defines the tesselation factor to apply to the disc
  39853. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39854. * @param mesh defines the hosting mesh (can be null)
  39855. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39856. */
  39857. function DiscGeometry(id, scene,
  39858. /**
  39859. * Defines the radius of the disc
  39860. */
  39861. radius,
  39862. /**
  39863. * Defines the tesselation factor to apply to the disc
  39864. */
  39865. tessellation, canBeRegenerated, mesh,
  39866. /**
  39867. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39868. */
  39869. side) {
  39870. if (mesh === void 0) { mesh = null; }
  39871. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39872. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39873. _this.radius = radius;
  39874. _this.tessellation = tessellation;
  39875. _this.side = side;
  39876. return _this;
  39877. }
  39878. DiscGeometry.prototype._regenerateVertexData = function () {
  39879. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39880. };
  39881. DiscGeometry.prototype.copy = function (id) {
  39882. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39883. };
  39884. return DiscGeometry;
  39885. }(_PrimitiveGeometry));
  39886. BABYLON.DiscGeometry = DiscGeometry;
  39887. /**
  39888. * Creates a new cylinder geometry
  39889. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39890. */
  39891. var CylinderGeometry = /** @class */ (function (_super) {
  39892. __extends(CylinderGeometry, _super);
  39893. /**
  39894. * Creates a new cylinder geometry
  39895. * @param id defines the unique ID of the geometry
  39896. * @param scene defines the hosting scene
  39897. * @param height defines the height of the cylinder
  39898. * @param diameterTop defines the diameter of the cylinder's top cap
  39899. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39900. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39901. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39902. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39903. * @param mesh defines the hosting mesh (can be null)
  39904. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39905. */
  39906. function CylinderGeometry(id, scene,
  39907. /**
  39908. * Defines the height of the cylinder
  39909. */
  39910. height,
  39911. /**
  39912. * Defines the diameter of the cylinder's top cap
  39913. */
  39914. diameterTop,
  39915. /**
  39916. * Defines the diameter of the cylinder's bottom cap
  39917. */
  39918. diameterBottom,
  39919. /**
  39920. * Defines the tessellation factor to apply to the cylinder
  39921. */
  39922. tessellation,
  39923. /**
  39924. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39925. */
  39926. subdivisions, canBeRegenerated, mesh,
  39927. /**
  39928. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39929. */
  39930. side) {
  39931. if (subdivisions === void 0) { subdivisions = 1; }
  39932. if (mesh === void 0) { mesh = null; }
  39933. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39934. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39935. _this.height = height;
  39936. _this.diameterTop = diameterTop;
  39937. _this.diameterBottom = diameterBottom;
  39938. _this.tessellation = tessellation;
  39939. _this.subdivisions = subdivisions;
  39940. _this.side = side;
  39941. return _this;
  39942. }
  39943. CylinderGeometry.prototype._regenerateVertexData = function () {
  39944. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39945. };
  39946. CylinderGeometry.prototype.copy = function (id) {
  39947. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39948. };
  39949. CylinderGeometry.prototype.serialize = function () {
  39950. var serializationObject = _super.prototype.serialize.call(this);
  39951. serializationObject.height = this.height;
  39952. serializationObject.diameterTop = this.diameterTop;
  39953. serializationObject.diameterBottom = this.diameterBottom;
  39954. serializationObject.tessellation = this.tessellation;
  39955. return serializationObject;
  39956. };
  39957. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39958. if (scene.getGeometryByID(parsedCylinder.id)) {
  39959. return null; // null since geometry could be something else than a cylinder...
  39960. }
  39961. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39962. if (BABYLON.Tags) {
  39963. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39964. }
  39965. scene.pushGeometry(cylinder, true);
  39966. return cylinder;
  39967. };
  39968. return CylinderGeometry;
  39969. }(_PrimitiveGeometry));
  39970. BABYLON.CylinderGeometry = CylinderGeometry;
  39971. /**
  39972. * Creates a new torus geometry
  39973. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39974. */
  39975. var TorusGeometry = /** @class */ (function (_super) {
  39976. __extends(TorusGeometry, _super);
  39977. /**
  39978. * Creates a new torus geometry
  39979. * @param id defines the unique ID of the geometry
  39980. * @param scene defines the hosting scene
  39981. * @param diameter defines the diameter of the torus
  39982. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39983. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39984. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39985. * @param mesh defines the hosting mesh (can be null)
  39986. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39987. */
  39988. function TorusGeometry(id, scene,
  39989. /**
  39990. * Defines the diameter of the torus
  39991. */
  39992. diameter,
  39993. /**
  39994. * Defines the thickness of the torus (ie. internal diameter)
  39995. */
  39996. thickness,
  39997. /**
  39998. * Defines the tesselation factor to apply to the torus
  39999. */
  40000. tessellation, canBeRegenerated, mesh,
  40001. /**
  40002. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40003. */
  40004. side) {
  40005. if (mesh === void 0) { mesh = null; }
  40006. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40007. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40008. _this.diameter = diameter;
  40009. _this.thickness = thickness;
  40010. _this.tessellation = tessellation;
  40011. _this.side = side;
  40012. return _this;
  40013. }
  40014. TorusGeometry.prototype._regenerateVertexData = function () {
  40015. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40016. };
  40017. TorusGeometry.prototype.copy = function (id) {
  40018. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40019. };
  40020. TorusGeometry.prototype.serialize = function () {
  40021. var serializationObject = _super.prototype.serialize.call(this);
  40022. serializationObject.diameter = this.diameter;
  40023. serializationObject.thickness = this.thickness;
  40024. serializationObject.tessellation = this.tessellation;
  40025. return serializationObject;
  40026. };
  40027. TorusGeometry.Parse = function (parsedTorus, scene) {
  40028. if (scene.getGeometryByID(parsedTorus.id)) {
  40029. return null; // null since geometry could be something else than a torus...
  40030. }
  40031. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40032. if (BABYLON.Tags) {
  40033. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40034. }
  40035. scene.pushGeometry(torus, true);
  40036. return torus;
  40037. };
  40038. return TorusGeometry;
  40039. }(_PrimitiveGeometry));
  40040. BABYLON.TorusGeometry = TorusGeometry;
  40041. /**
  40042. * Creates a new ground geometry
  40043. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40044. */
  40045. var GroundGeometry = /** @class */ (function (_super) {
  40046. __extends(GroundGeometry, _super);
  40047. /**
  40048. * Creates a new ground geometry
  40049. * @param id defines the unique ID of the geometry
  40050. * @param scene defines the hosting scene
  40051. * @param width defines the width of the ground
  40052. * @param height defines the height of the ground
  40053. * @param subdivisions defines the subdivisions to apply to the ground
  40054. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40055. * @param mesh defines the hosting mesh (can be null)
  40056. */
  40057. function GroundGeometry(id, scene,
  40058. /**
  40059. * Defines the width of the ground
  40060. */
  40061. width,
  40062. /**
  40063. * Defines the height of the ground
  40064. */
  40065. height,
  40066. /**
  40067. * Defines the subdivisions to apply to the ground
  40068. */
  40069. subdivisions, canBeRegenerated, mesh) {
  40070. if (mesh === void 0) { mesh = null; }
  40071. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40072. _this.width = width;
  40073. _this.height = height;
  40074. _this.subdivisions = subdivisions;
  40075. return _this;
  40076. }
  40077. GroundGeometry.prototype._regenerateVertexData = function () {
  40078. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40079. };
  40080. GroundGeometry.prototype.copy = function (id) {
  40081. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40082. };
  40083. GroundGeometry.prototype.serialize = function () {
  40084. var serializationObject = _super.prototype.serialize.call(this);
  40085. serializationObject.width = this.width;
  40086. serializationObject.height = this.height;
  40087. serializationObject.subdivisions = this.subdivisions;
  40088. return serializationObject;
  40089. };
  40090. GroundGeometry.Parse = function (parsedGround, scene) {
  40091. if (scene.getGeometryByID(parsedGround.id)) {
  40092. return null; // null since geometry could be something else than a ground...
  40093. }
  40094. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40095. if (BABYLON.Tags) {
  40096. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40097. }
  40098. scene.pushGeometry(ground, true);
  40099. return ground;
  40100. };
  40101. return GroundGeometry;
  40102. }(_PrimitiveGeometry));
  40103. BABYLON.GroundGeometry = GroundGeometry;
  40104. /**
  40105. * Creates a tiled ground geometry
  40106. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40107. */
  40108. var TiledGroundGeometry = /** @class */ (function (_super) {
  40109. __extends(TiledGroundGeometry, _super);
  40110. /**
  40111. * Creates a tiled ground geometry
  40112. * @param id defines the unique ID of the geometry
  40113. * @param scene defines the hosting scene
  40114. * @param xmin defines the minimum value on X axis
  40115. * @param zmin defines the minimum value on Z axis
  40116. * @param xmax defines the maximum value on X axis
  40117. * @param zmax defines the maximum value on Z axis
  40118. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40119. * @param precision defines the precision to use when computing the tiles
  40120. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40121. * @param mesh defines the hosting mesh (can be null)
  40122. */
  40123. function TiledGroundGeometry(id, scene,
  40124. /**
  40125. * Defines the minimum value on X axis
  40126. */
  40127. xmin,
  40128. /**
  40129. * Defines the minimum value on Z axis
  40130. */
  40131. zmin,
  40132. /**
  40133. * Defines the maximum value on X axis
  40134. */
  40135. xmax,
  40136. /**
  40137. * Defines the maximum value on Z axis
  40138. */
  40139. zmax,
  40140. /**
  40141. * Defines the subdivisions to apply to the ground
  40142. */
  40143. subdivisions,
  40144. /**
  40145. * Defines the precision to use when computing the tiles
  40146. */
  40147. precision, canBeRegenerated, mesh) {
  40148. if (mesh === void 0) { mesh = null; }
  40149. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40150. _this.xmin = xmin;
  40151. _this.zmin = zmin;
  40152. _this.xmax = xmax;
  40153. _this.zmax = zmax;
  40154. _this.subdivisions = subdivisions;
  40155. _this.precision = precision;
  40156. return _this;
  40157. }
  40158. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40159. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40160. };
  40161. TiledGroundGeometry.prototype.copy = function (id) {
  40162. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40163. };
  40164. return TiledGroundGeometry;
  40165. }(_PrimitiveGeometry));
  40166. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40167. /**
  40168. * Creates a plane geometry
  40169. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40170. */
  40171. var PlaneGeometry = /** @class */ (function (_super) {
  40172. __extends(PlaneGeometry, _super);
  40173. /**
  40174. * Creates a plane geometry
  40175. * @param id defines the unique ID of the geometry
  40176. * @param scene defines the hosting scene
  40177. * @param size defines the size of the plane (width === height)
  40178. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40179. * @param mesh defines the hosting mesh (can be null)
  40180. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40181. */
  40182. function PlaneGeometry(id, scene,
  40183. /**
  40184. * Defines the size of the plane (width === height)
  40185. */
  40186. size, canBeRegenerated, mesh,
  40187. /**
  40188. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40189. */
  40190. side) {
  40191. if (mesh === void 0) { mesh = null; }
  40192. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40193. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40194. _this.size = size;
  40195. _this.side = side;
  40196. return _this;
  40197. }
  40198. PlaneGeometry.prototype._regenerateVertexData = function () {
  40199. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40200. };
  40201. PlaneGeometry.prototype.copy = function (id) {
  40202. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40203. };
  40204. PlaneGeometry.prototype.serialize = function () {
  40205. var serializationObject = _super.prototype.serialize.call(this);
  40206. serializationObject.size = this.size;
  40207. return serializationObject;
  40208. };
  40209. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40210. if (scene.getGeometryByID(parsedPlane.id)) {
  40211. return null; // null since geometry could be something else than a ground...
  40212. }
  40213. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40214. if (BABYLON.Tags) {
  40215. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40216. }
  40217. scene.pushGeometry(plane, true);
  40218. return plane;
  40219. };
  40220. return PlaneGeometry;
  40221. }(_PrimitiveGeometry));
  40222. BABYLON.PlaneGeometry = PlaneGeometry;
  40223. /**
  40224. * Creates a torus knot geometry
  40225. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40226. */
  40227. var TorusKnotGeometry = /** @class */ (function (_super) {
  40228. __extends(TorusKnotGeometry, _super);
  40229. /**
  40230. * Creates a torus knot geometry
  40231. * @param id defines the unique ID of the geometry
  40232. * @param scene defines the hosting scene
  40233. * @param radius defines the radius of the torus knot
  40234. * @param tube defines the thickness of the torus knot tube
  40235. * @param radialSegments defines the number of radial segments
  40236. * @param tubularSegments defines the number of tubular segments
  40237. * @param p defines the first number of windings
  40238. * @param q defines the second number of windings
  40239. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40240. * @param mesh defines the hosting mesh (can be null)
  40241. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40242. */
  40243. function TorusKnotGeometry(id, scene,
  40244. /**
  40245. * Defines the radius of the torus knot
  40246. */
  40247. radius,
  40248. /**
  40249. * Defines the thickness of the torus knot tube
  40250. */
  40251. tube,
  40252. /**
  40253. * Defines the number of radial segments
  40254. */
  40255. radialSegments,
  40256. /**
  40257. * Defines the number of tubular segments
  40258. */
  40259. tubularSegments,
  40260. /**
  40261. * Defines the first number of windings
  40262. */
  40263. p,
  40264. /**
  40265. * Defines the second number of windings
  40266. */
  40267. q, canBeRegenerated, mesh,
  40268. /**
  40269. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40270. */
  40271. side) {
  40272. if (mesh === void 0) { mesh = null; }
  40273. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40274. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40275. _this.radius = radius;
  40276. _this.tube = tube;
  40277. _this.radialSegments = radialSegments;
  40278. _this.tubularSegments = tubularSegments;
  40279. _this.p = p;
  40280. _this.q = q;
  40281. _this.side = side;
  40282. return _this;
  40283. }
  40284. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40285. 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 });
  40286. };
  40287. TorusKnotGeometry.prototype.copy = function (id) {
  40288. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40289. };
  40290. TorusKnotGeometry.prototype.serialize = function () {
  40291. var serializationObject = _super.prototype.serialize.call(this);
  40292. serializationObject.radius = this.radius;
  40293. serializationObject.tube = this.tube;
  40294. serializationObject.radialSegments = this.radialSegments;
  40295. serializationObject.tubularSegments = this.tubularSegments;
  40296. serializationObject.p = this.p;
  40297. serializationObject.q = this.q;
  40298. return serializationObject;
  40299. };
  40300. ;
  40301. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40302. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40303. return null; // null since geometry could be something else than a ground...
  40304. }
  40305. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40306. if (BABYLON.Tags) {
  40307. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40308. }
  40309. scene.pushGeometry(torusKnot, true);
  40310. return torusKnot;
  40311. };
  40312. return TorusKnotGeometry;
  40313. }(_PrimitiveGeometry));
  40314. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40315. //}
  40316. })(BABYLON || (BABYLON = {}));
  40317. //# sourceMappingURL=babylon.geometry.js.map
  40318. var BABYLON;
  40319. (function (BABYLON) {
  40320. /**
  40321. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40322. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40323. */
  40324. var PostProcessManager = /** @class */ (function () {
  40325. /**
  40326. * Creates a new instance PostProcess
  40327. * @param scene The scene that the post process is associated with.
  40328. */
  40329. function PostProcessManager(scene) {
  40330. this._vertexBuffers = {};
  40331. this._scene = scene;
  40332. }
  40333. PostProcessManager.prototype._prepareBuffers = function () {
  40334. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40335. return;
  40336. }
  40337. // VBO
  40338. var vertices = [];
  40339. vertices.push(1, 1);
  40340. vertices.push(-1, 1);
  40341. vertices.push(-1, -1);
  40342. vertices.push(1, -1);
  40343. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40344. this._buildIndexBuffer();
  40345. };
  40346. PostProcessManager.prototype._buildIndexBuffer = function () {
  40347. // Indices
  40348. var indices = [];
  40349. indices.push(0);
  40350. indices.push(1);
  40351. indices.push(2);
  40352. indices.push(0);
  40353. indices.push(2);
  40354. indices.push(3);
  40355. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40356. };
  40357. /**
  40358. * Rebuilds the vertex buffers of the manager.
  40359. */
  40360. PostProcessManager.prototype._rebuild = function () {
  40361. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40362. if (!vb) {
  40363. return;
  40364. }
  40365. vb._rebuild();
  40366. this._buildIndexBuffer();
  40367. };
  40368. // Methods
  40369. /**
  40370. * Prepares a frame to be run through a post process.
  40371. * @param sourceTexture The input texture to the post procesess. (default: null)
  40372. * @param postProcesses An array of post processes to be run. (default: null)
  40373. * @returns True if the post processes were able to be run.
  40374. */
  40375. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40376. if (sourceTexture === void 0) { sourceTexture = null; }
  40377. if (postProcesses === void 0) { postProcesses = null; }
  40378. var camera = this._scene.activeCamera;
  40379. if (!camera) {
  40380. return false;
  40381. }
  40382. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40383. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40384. return false;
  40385. }
  40386. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40387. return true;
  40388. };
  40389. /**
  40390. * Manually render a set of post processes to a texture.
  40391. * @param postProcesses An array of post processes to be run.
  40392. * @param targetTexture The target texture to render to.
  40393. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40394. */
  40395. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40396. if (targetTexture === void 0) { targetTexture = null; }
  40397. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40398. var engine = this._scene.getEngine();
  40399. for (var index = 0; index < postProcesses.length; index++) {
  40400. if (index < postProcesses.length - 1) {
  40401. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40402. }
  40403. else {
  40404. if (targetTexture) {
  40405. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40406. }
  40407. else {
  40408. engine.restoreDefaultFramebuffer();
  40409. }
  40410. }
  40411. var pp = postProcesses[index];
  40412. var effect = pp.apply();
  40413. if (effect) {
  40414. pp.onBeforeRenderObservable.notifyObservers(effect);
  40415. // VBOs
  40416. this._prepareBuffers();
  40417. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40418. // Draw order
  40419. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40420. pp.onAfterRenderObservable.notifyObservers(effect);
  40421. }
  40422. }
  40423. // Restore depth buffer
  40424. engine.setDepthBuffer(true);
  40425. engine.setDepthWrite(true);
  40426. };
  40427. /**
  40428. * Finalize the result of the output of the postprocesses.
  40429. * @param doNotPresent If true the result will not be displayed to the screen.
  40430. * @param targetTexture The target texture to render to.
  40431. * @param faceIndex The index of the face to bind the target texture to.
  40432. * @param postProcesses The array of post processes to render.
  40433. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40434. */
  40435. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40436. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40437. var camera = this._scene.activeCamera;
  40438. if (!camera) {
  40439. return;
  40440. }
  40441. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40442. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40443. return;
  40444. }
  40445. var engine = this._scene.getEngine();
  40446. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40447. var pp = postProcesses[index];
  40448. if (index < len - 1) {
  40449. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40450. }
  40451. else {
  40452. if (targetTexture) {
  40453. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40454. pp._outputTexture = targetTexture;
  40455. }
  40456. else {
  40457. engine.restoreDefaultFramebuffer();
  40458. pp._outputTexture = null;
  40459. }
  40460. }
  40461. if (doNotPresent) {
  40462. break;
  40463. }
  40464. var effect = pp.apply();
  40465. if (effect) {
  40466. pp.onBeforeRenderObservable.notifyObservers(effect);
  40467. // VBOs
  40468. this._prepareBuffers();
  40469. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40470. // Draw order
  40471. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40472. pp.onAfterRenderObservable.notifyObservers(effect);
  40473. }
  40474. }
  40475. // Restore states
  40476. engine.setDepthBuffer(true);
  40477. engine.setDepthWrite(true);
  40478. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40479. };
  40480. /**
  40481. * Disposes of the post process manager.
  40482. */
  40483. PostProcessManager.prototype.dispose = function () {
  40484. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40485. if (buffer) {
  40486. buffer.dispose();
  40487. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40488. }
  40489. if (this._indexBuffer) {
  40490. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40491. this._indexBuffer = null;
  40492. }
  40493. };
  40494. return PostProcessManager;
  40495. }());
  40496. BABYLON.PostProcessManager = PostProcessManager;
  40497. })(BABYLON || (BABYLON = {}));
  40498. //# sourceMappingURL=babylon.postProcessManager.js.map
  40499. var BABYLON;
  40500. (function (BABYLON) {
  40501. /**
  40502. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40503. */
  40504. var PerformanceMonitor = /** @class */ (function () {
  40505. /**
  40506. * constructor
  40507. * @param frameSampleSize The number of samples required to saturate the sliding window
  40508. */
  40509. function PerformanceMonitor(frameSampleSize) {
  40510. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40511. this._enabled = true;
  40512. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40513. }
  40514. /**
  40515. * Samples current frame
  40516. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40517. */
  40518. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40519. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40520. if (!this._enabled)
  40521. return;
  40522. if (this._lastFrameTimeMs != null) {
  40523. var dt = timeMs - this._lastFrameTimeMs;
  40524. this._rollingFrameTime.add(dt);
  40525. }
  40526. this._lastFrameTimeMs = timeMs;
  40527. };
  40528. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40529. /**
  40530. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40531. * @return Average frame time in milliseconds
  40532. */
  40533. get: function () {
  40534. return this._rollingFrameTime.average;
  40535. },
  40536. enumerable: true,
  40537. configurable: true
  40538. });
  40539. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40540. /**
  40541. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40542. * @return Frame time variance in milliseconds squared
  40543. */
  40544. get: function () {
  40545. return this._rollingFrameTime.variance;
  40546. },
  40547. enumerable: true,
  40548. configurable: true
  40549. });
  40550. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40551. /**
  40552. * Returns the frame time of the most recent frame
  40553. * @return Frame time in milliseconds
  40554. */
  40555. get: function () {
  40556. return this._rollingFrameTime.history(0);
  40557. },
  40558. enumerable: true,
  40559. configurable: true
  40560. });
  40561. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40562. /**
  40563. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40564. * @return Framerate in frames per second
  40565. */
  40566. get: function () {
  40567. return 1000.0 / this._rollingFrameTime.average;
  40568. },
  40569. enumerable: true,
  40570. configurable: true
  40571. });
  40572. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40573. /**
  40574. * Returns the average framerate in frames per second using the most recent frame time
  40575. * @return Framerate in frames per second
  40576. */
  40577. get: function () {
  40578. var history = this._rollingFrameTime.history(0);
  40579. if (history === 0) {
  40580. return 0;
  40581. }
  40582. return 1000.0 / history;
  40583. },
  40584. enumerable: true,
  40585. configurable: true
  40586. });
  40587. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40588. /**
  40589. * Returns true if enough samples have been taken to completely fill the sliding window
  40590. * @return true if saturated
  40591. */
  40592. get: function () {
  40593. return this._rollingFrameTime.isSaturated();
  40594. },
  40595. enumerable: true,
  40596. configurable: true
  40597. });
  40598. /**
  40599. * Enables contributions to the sliding window sample set
  40600. */
  40601. PerformanceMonitor.prototype.enable = function () {
  40602. this._enabled = true;
  40603. };
  40604. /**
  40605. * Disables contributions to the sliding window sample set
  40606. * Samples will not be interpolated over the disabled period
  40607. */
  40608. PerformanceMonitor.prototype.disable = function () {
  40609. this._enabled = false;
  40610. //clear last sample to avoid interpolating over the disabled period when next enabled
  40611. this._lastFrameTimeMs = null;
  40612. };
  40613. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40614. /**
  40615. * Returns true if sampling is enabled
  40616. * @return true if enabled
  40617. */
  40618. get: function () {
  40619. return this._enabled;
  40620. },
  40621. enumerable: true,
  40622. configurable: true
  40623. });
  40624. /**
  40625. * Resets performance monitor
  40626. */
  40627. PerformanceMonitor.prototype.reset = function () {
  40628. //clear last sample to avoid interpolating over the disabled period when next enabled
  40629. this._lastFrameTimeMs = null;
  40630. //wipe record
  40631. this._rollingFrameTime.reset();
  40632. };
  40633. return PerformanceMonitor;
  40634. }());
  40635. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40636. /**
  40637. * RollingAverage
  40638. *
  40639. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40640. */
  40641. var RollingAverage = /** @class */ (function () {
  40642. /**
  40643. * constructor
  40644. * @param length The number of samples required to saturate the sliding window
  40645. */
  40646. function RollingAverage(length) {
  40647. this._samples = new Array(length);
  40648. this.reset();
  40649. }
  40650. /**
  40651. * Adds a sample to the sample set
  40652. * @param v The sample value
  40653. */
  40654. RollingAverage.prototype.add = function (v) {
  40655. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40656. var delta;
  40657. //we need to check if we've already wrapped round
  40658. if (this.isSaturated()) {
  40659. //remove bottom of stack from mean
  40660. var bottomValue = this._samples[this._pos];
  40661. delta = bottomValue - this.average;
  40662. this.average -= delta / (this._sampleCount - 1);
  40663. this._m2 -= delta * (bottomValue - this.average);
  40664. }
  40665. else {
  40666. this._sampleCount++;
  40667. }
  40668. //add new value to mean
  40669. delta = v - this.average;
  40670. this.average += delta / (this._sampleCount);
  40671. this._m2 += delta * (v - this.average);
  40672. //set the new variance
  40673. this.variance = this._m2 / (this._sampleCount - 1);
  40674. this._samples[this._pos] = v;
  40675. this._pos++;
  40676. this._pos %= this._samples.length; //positive wrap around
  40677. };
  40678. /**
  40679. * Returns previously added values or null if outside of history or outside the sliding window domain
  40680. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40681. * @return Value previously recorded with add() or null if outside of range
  40682. */
  40683. RollingAverage.prototype.history = function (i) {
  40684. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40685. return 0;
  40686. }
  40687. var i0 = this._wrapPosition(this._pos - 1.0);
  40688. return this._samples[this._wrapPosition(i0 - i)];
  40689. };
  40690. /**
  40691. * Returns true if enough samples have been taken to completely fill the sliding window
  40692. * @return true if sample-set saturated
  40693. */
  40694. RollingAverage.prototype.isSaturated = function () {
  40695. return this._sampleCount >= this._samples.length;
  40696. };
  40697. /**
  40698. * Resets the rolling average (equivalent to 0 samples taken so far)
  40699. */
  40700. RollingAverage.prototype.reset = function () {
  40701. this.average = 0;
  40702. this.variance = 0;
  40703. this._sampleCount = 0;
  40704. this._pos = 0;
  40705. this._m2 = 0;
  40706. };
  40707. /**
  40708. * Wraps a value around the sample range boundaries
  40709. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40710. * @return Wrapped position in sample range
  40711. */
  40712. RollingAverage.prototype._wrapPosition = function (i) {
  40713. var max = this._samples.length;
  40714. return ((i % max) + max) % max;
  40715. };
  40716. return RollingAverage;
  40717. }());
  40718. BABYLON.RollingAverage = RollingAverage;
  40719. })(BABYLON || (BABYLON = {}));
  40720. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40721. var BABYLON;
  40722. (function (BABYLON) {
  40723. /**
  40724. * This groups together the common properties used for image processing either in direct forward pass
  40725. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40726. * or not.
  40727. */
  40728. var ImageProcessingConfiguration = /** @class */ (function () {
  40729. function ImageProcessingConfiguration() {
  40730. /**
  40731. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40732. */
  40733. this.colorCurves = new BABYLON.ColorCurves();
  40734. this._colorCurvesEnabled = false;
  40735. this._colorGradingEnabled = false;
  40736. this._colorGradingWithGreenDepth = true;
  40737. this._colorGradingBGR = true;
  40738. this._exposure = 1.0;
  40739. this._toneMappingEnabled = false;
  40740. this._contrast = 1.0;
  40741. /**
  40742. * Vignette stretch size.
  40743. */
  40744. this.vignetteStretch = 0;
  40745. /**
  40746. * Vignette centre X Offset.
  40747. */
  40748. this.vignetteCentreX = 0;
  40749. /**
  40750. * Vignette centre Y Offset.
  40751. */
  40752. this.vignetteCentreY = 0;
  40753. /**
  40754. * Vignette weight or intensity of the vignette effect.
  40755. */
  40756. this.vignetteWeight = 1.5;
  40757. /**
  40758. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40759. * if vignetteEnabled is set to true.
  40760. */
  40761. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40762. /**
  40763. * Camera field of view used by the Vignette effect.
  40764. */
  40765. this.vignetteCameraFov = 0.5;
  40766. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40767. this._vignetteEnabled = false;
  40768. this._applyByPostProcess = false;
  40769. this._isEnabled = true;
  40770. /**
  40771. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40772. */
  40773. this.onUpdateParameters = new BABYLON.Observable();
  40774. }
  40775. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40776. /**
  40777. * Gets wether the color curves effect is enabled.
  40778. */
  40779. get: function () {
  40780. return this._colorCurvesEnabled;
  40781. },
  40782. /**
  40783. * Sets wether the color curves effect is enabled.
  40784. */
  40785. set: function (value) {
  40786. if (this._colorCurvesEnabled === value) {
  40787. return;
  40788. }
  40789. this._colorCurvesEnabled = value;
  40790. this._updateParameters();
  40791. },
  40792. enumerable: true,
  40793. configurable: true
  40794. });
  40795. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40796. /**
  40797. * Gets wether the color grading effect is enabled.
  40798. */
  40799. get: function () {
  40800. return this._colorGradingEnabled;
  40801. },
  40802. /**
  40803. * Sets wether the color grading effect is enabled.
  40804. */
  40805. set: function (value) {
  40806. if (this._colorGradingEnabled === value) {
  40807. return;
  40808. }
  40809. this._colorGradingEnabled = value;
  40810. this._updateParameters();
  40811. },
  40812. enumerable: true,
  40813. configurable: true
  40814. });
  40815. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40816. /**
  40817. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40818. */
  40819. get: function () {
  40820. return this._colorGradingWithGreenDepth;
  40821. },
  40822. /**
  40823. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40824. */
  40825. set: function (value) {
  40826. if (this._colorGradingWithGreenDepth === value) {
  40827. return;
  40828. }
  40829. this._colorGradingWithGreenDepth = value;
  40830. this._updateParameters();
  40831. },
  40832. enumerable: true,
  40833. configurable: true
  40834. });
  40835. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40836. /**
  40837. * Gets wether the color grading texture contains BGR values.
  40838. */
  40839. get: function () {
  40840. return this._colorGradingBGR;
  40841. },
  40842. /**
  40843. * Sets wether the color grading texture contains BGR values.
  40844. */
  40845. set: function (value) {
  40846. if (this._colorGradingBGR === value) {
  40847. return;
  40848. }
  40849. this._colorGradingBGR = value;
  40850. this._updateParameters();
  40851. },
  40852. enumerable: true,
  40853. configurable: true
  40854. });
  40855. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40856. /**
  40857. * Gets the Exposure used in the effect.
  40858. */
  40859. get: function () {
  40860. return this._exposure;
  40861. },
  40862. /**
  40863. * Sets the Exposure used in the effect.
  40864. */
  40865. set: function (value) {
  40866. if (this._exposure === value) {
  40867. return;
  40868. }
  40869. this._exposure = value;
  40870. this._updateParameters();
  40871. },
  40872. enumerable: true,
  40873. configurable: true
  40874. });
  40875. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40876. /**
  40877. * Gets wether the tone mapping effect is enabled.
  40878. */
  40879. get: function () {
  40880. return this._toneMappingEnabled;
  40881. },
  40882. /**
  40883. * Sets wether the tone mapping effect is enabled.
  40884. */
  40885. set: function (value) {
  40886. if (this._toneMappingEnabled === value) {
  40887. return;
  40888. }
  40889. this._toneMappingEnabled = value;
  40890. this._updateParameters();
  40891. },
  40892. enumerable: true,
  40893. configurable: true
  40894. });
  40895. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40896. /**
  40897. * Gets the contrast used in the effect.
  40898. */
  40899. get: function () {
  40900. return this._contrast;
  40901. },
  40902. /**
  40903. * Sets the contrast used in the effect.
  40904. */
  40905. set: function (value) {
  40906. if (this._contrast === value) {
  40907. return;
  40908. }
  40909. this._contrast = value;
  40910. this._updateParameters();
  40911. },
  40912. enumerable: true,
  40913. configurable: true
  40914. });
  40915. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40916. /**
  40917. * Gets the vignette blend mode allowing different kind of effect.
  40918. */
  40919. get: function () {
  40920. return this._vignetteBlendMode;
  40921. },
  40922. /**
  40923. * Sets the vignette blend mode allowing different kind of effect.
  40924. */
  40925. set: function (value) {
  40926. if (this._vignetteBlendMode === value) {
  40927. return;
  40928. }
  40929. this._vignetteBlendMode = value;
  40930. this._updateParameters();
  40931. },
  40932. enumerable: true,
  40933. configurable: true
  40934. });
  40935. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40936. /**
  40937. * Gets wether the vignette effect is enabled.
  40938. */
  40939. get: function () {
  40940. return this._vignetteEnabled;
  40941. },
  40942. /**
  40943. * Sets wether the vignette effect is enabled.
  40944. */
  40945. set: function (value) {
  40946. if (this._vignetteEnabled === value) {
  40947. return;
  40948. }
  40949. this._vignetteEnabled = value;
  40950. this._updateParameters();
  40951. },
  40952. enumerable: true,
  40953. configurable: true
  40954. });
  40955. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40956. /**
  40957. * Gets wether the image processing is applied through a post process or not.
  40958. */
  40959. get: function () {
  40960. return this._applyByPostProcess;
  40961. },
  40962. /**
  40963. * Sets wether the image processing is applied through a post process or not.
  40964. */
  40965. set: function (value) {
  40966. if (this._applyByPostProcess === value) {
  40967. return;
  40968. }
  40969. this._applyByPostProcess = value;
  40970. this._updateParameters();
  40971. },
  40972. enumerable: true,
  40973. configurable: true
  40974. });
  40975. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40976. /**
  40977. * Gets wether the image processing is enabled or not.
  40978. */
  40979. get: function () {
  40980. return this._isEnabled;
  40981. },
  40982. /**
  40983. * Sets wether the image processing is enabled or not.
  40984. */
  40985. set: function (value) {
  40986. if (this._isEnabled === value) {
  40987. return;
  40988. }
  40989. this._isEnabled = value;
  40990. this._updateParameters();
  40991. },
  40992. enumerable: true,
  40993. configurable: true
  40994. });
  40995. /**
  40996. * Method called each time the image processing information changes requires to recompile the effect.
  40997. */
  40998. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40999. this.onUpdateParameters.notifyObservers(this);
  41000. };
  41001. ImageProcessingConfiguration.prototype.getClassName = function () {
  41002. return "ImageProcessingConfiguration";
  41003. };
  41004. /**
  41005. * Prepare the list of uniforms associated with the Image Processing effects.
  41006. * @param uniformsList The list of uniforms used in the effect
  41007. * @param defines the list of defines currently in use
  41008. */
  41009. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41010. if (defines.EXPOSURE) {
  41011. uniforms.push("exposureLinear");
  41012. }
  41013. if (defines.CONTRAST) {
  41014. uniforms.push("contrast");
  41015. }
  41016. if (defines.COLORGRADING) {
  41017. uniforms.push("colorTransformSettings");
  41018. }
  41019. if (defines.VIGNETTE) {
  41020. uniforms.push("vInverseScreenSize");
  41021. uniforms.push("vignetteSettings1");
  41022. uniforms.push("vignetteSettings2");
  41023. }
  41024. if (defines.COLORCURVES) {
  41025. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41026. }
  41027. };
  41028. /**
  41029. * Prepare the list of samplers associated with the Image Processing effects.
  41030. * @param uniformsList The list of uniforms used in the effect
  41031. * @param defines the list of defines currently in use
  41032. */
  41033. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41034. if (defines.COLORGRADING) {
  41035. samplersList.push("txColorTransform");
  41036. }
  41037. };
  41038. /**
  41039. * Prepare the list of defines associated to the shader.
  41040. * @param defines the list of defines to complete
  41041. */
  41042. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41043. if (forPostProcess === void 0) { forPostProcess = false; }
  41044. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41045. defines.VIGNETTE = false;
  41046. defines.TONEMAPPING = false;
  41047. defines.CONTRAST = false;
  41048. defines.EXPOSURE = false;
  41049. defines.COLORCURVES = false;
  41050. defines.COLORGRADING = false;
  41051. defines.COLORGRADING3D = false;
  41052. defines.IMAGEPROCESSING = false;
  41053. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41054. return;
  41055. }
  41056. defines.VIGNETTE = this.vignetteEnabled;
  41057. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41058. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41059. defines.TONEMAPPING = this.toneMappingEnabled;
  41060. defines.CONTRAST = (this.contrast !== 1.0);
  41061. defines.EXPOSURE = (this.exposure !== 1.0);
  41062. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41063. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41064. if (defines.COLORGRADING) {
  41065. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41066. }
  41067. else {
  41068. defines.COLORGRADING3D = false;
  41069. }
  41070. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41071. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41072. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41073. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41074. };
  41075. /**
  41076. * Returns true if all the image processing information are ready.
  41077. */
  41078. ImageProcessingConfiguration.prototype.isReady = function () {
  41079. // Color Grading texure can not be none blocking.
  41080. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41081. };
  41082. /**
  41083. * Binds the image processing to the shader.
  41084. * @param effect The effect to bind to
  41085. */
  41086. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41087. if (aspectRatio === void 0) { aspectRatio = 1; }
  41088. // Color Curves
  41089. if (this._colorCurvesEnabled && this.colorCurves) {
  41090. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41091. }
  41092. // Vignette
  41093. if (this._vignetteEnabled) {
  41094. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41095. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41096. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41097. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41098. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41099. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41100. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41101. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41102. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41103. var vignettePower = -2.0 * this.vignetteWeight;
  41104. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41105. }
  41106. // Exposure
  41107. effect.setFloat("exposureLinear", this.exposure);
  41108. // Contrast
  41109. effect.setFloat("contrast", this.contrast);
  41110. // Color transform settings
  41111. if (this.colorGradingTexture) {
  41112. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41113. var textureSize = this.colorGradingTexture.getSize().height;
  41114. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41115. 0.5 / textureSize, // textureOffset
  41116. textureSize, // textureSize
  41117. this.colorGradingTexture.level // weight
  41118. );
  41119. }
  41120. };
  41121. /**
  41122. * Clones the current image processing instance.
  41123. * @return The cloned image processing
  41124. */
  41125. ImageProcessingConfiguration.prototype.clone = function () {
  41126. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41127. };
  41128. /**
  41129. * Serializes the current image processing instance to a json representation.
  41130. * @return a JSON representation
  41131. */
  41132. ImageProcessingConfiguration.prototype.serialize = function () {
  41133. return BABYLON.SerializationHelper.Serialize(this);
  41134. };
  41135. /**
  41136. * Parses the image processing from a json representation.
  41137. * @param source the JSON source to parse
  41138. * @return The parsed image processing
  41139. */
  41140. ImageProcessingConfiguration.Parse = function (source) {
  41141. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41142. };
  41143. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41144. /**
  41145. * Used to apply the vignette as a mix with the pixel color.
  41146. */
  41147. get: function () {
  41148. return this._VIGNETTEMODE_MULTIPLY;
  41149. },
  41150. enumerable: true,
  41151. configurable: true
  41152. });
  41153. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41154. /**
  41155. * Used to apply the vignette as a replacement of the pixel color.
  41156. */
  41157. get: function () {
  41158. return this._VIGNETTEMODE_OPAQUE;
  41159. },
  41160. enumerable: true,
  41161. configurable: true
  41162. });
  41163. // Static constants associated to the image processing.
  41164. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41165. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41166. __decorate([
  41167. BABYLON.serializeAsColorCurves()
  41168. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41169. __decorate([
  41170. BABYLON.serialize()
  41171. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41172. __decorate([
  41173. BABYLON.serializeAsTexture()
  41174. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41175. __decorate([
  41176. BABYLON.serialize()
  41177. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41178. __decorate([
  41179. BABYLON.serialize()
  41180. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41181. __decorate([
  41182. BABYLON.serialize()
  41183. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41184. __decorate([
  41185. BABYLON.serialize()
  41186. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41187. __decorate([
  41188. BABYLON.serialize()
  41189. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41190. __decorate([
  41191. BABYLON.serialize()
  41192. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41193. __decorate([
  41194. BABYLON.serialize()
  41195. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41196. __decorate([
  41197. BABYLON.serialize()
  41198. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41199. __decorate([
  41200. BABYLON.serialize()
  41201. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41202. __decorate([
  41203. BABYLON.serialize()
  41204. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41205. __decorate([
  41206. BABYLON.serializeAsColor4()
  41207. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41208. __decorate([
  41209. BABYLON.serialize()
  41210. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41211. __decorate([
  41212. BABYLON.serialize()
  41213. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41214. __decorate([
  41215. BABYLON.serialize()
  41216. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41217. __decorate([
  41218. BABYLON.serialize()
  41219. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41220. __decorate([
  41221. BABYLON.serialize()
  41222. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41223. return ImageProcessingConfiguration;
  41224. }());
  41225. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41226. })(BABYLON || (BABYLON = {}));
  41227. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41228. var BABYLON;
  41229. (function (BABYLON) {
  41230. /**
  41231. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41232. * It can help converting any input color in a desired output one. This can then be used to create effects
  41233. * from sepia, black and white to sixties or futuristic rendering...
  41234. *
  41235. * The only supported format is currently 3dl.
  41236. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41237. */
  41238. var ColorGradingTexture = /** @class */ (function (_super) {
  41239. __extends(ColorGradingTexture, _super);
  41240. /**
  41241. * Instantiates a ColorGradingTexture from the following parameters.
  41242. *
  41243. * @param url The location of the color gradind data (currently only supporting 3dl)
  41244. * @param scene The scene the texture will be used in
  41245. */
  41246. function ColorGradingTexture(url, scene) {
  41247. var _this = _super.call(this, scene) || this;
  41248. if (!url) {
  41249. return _this;
  41250. }
  41251. _this._engine = scene.getEngine();
  41252. _this._textureMatrix = BABYLON.Matrix.Identity();
  41253. _this.name = url;
  41254. _this.url = url;
  41255. _this.hasAlpha = false;
  41256. _this.isCube = false;
  41257. _this.is3D = _this._engine.webGLVersion > 1;
  41258. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41259. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41260. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41261. _this.anisotropicFilteringLevel = 1;
  41262. _this._texture = _this._getFromCache(url, true);
  41263. if (!_this._texture) {
  41264. if (!scene.useDelayedTextureLoading) {
  41265. _this.loadTexture();
  41266. }
  41267. else {
  41268. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41269. }
  41270. }
  41271. return _this;
  41272. }
  41273. /**
  41274. * Returns the texture matrix used in most of the material.
  41275. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41276. */
  41277. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41278. return this._textureMatrix;
  41279. };
  41280. /**
  41281. * Occurs when the file being loaded is a .3dl LUT file.
  41282. */
  41283. ColorGradingTexture.prototype.load3dlTexture = function () {
  41284. var engine = this._engine;
  41285. var texture;
  41286. if (engine.webGLVersion === 1) {
  41287. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41288. }
  41289. else {
  41290. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41291. }
  41292. this._texture = texture;
  41293. var callback = function (text) {
  41294. if (typeof text !== "string") {
  41295. return;
  41296. }
  41297. var data = null;
  41298. var tempData = null;
  41299. var line;
  41300. var lines = text.split('\n');
  41301. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41302. var maxColor = 0;
  41303. for (var i = 0; i < lines.length; i++) {
  41304. line = lines[i];
  41305. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41306. continue;
  41307. if (line.indexOf('#') === 0)
  41308. continue;
  41309. var words = line.split(" ");
  41310. if (size === 0) {
  41311. // Number of space + one
  41312. size = words.length;
  41313. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41314. tempData = new Float32Array(size * size * size * 4);
  41315. continue;
  41316. }
  41317. if (size != 0) {
  41318. var r = Math.max(parseInt(words[0]), 0);
  41319. var g = Math.max(parseInt(words[1]), 0);
  41320. var b = Math.max(parseInt(words[2]), 0);
  41321. maxColor = Math.max(r, maxColor);
  41322. maxColor = Math.max(g, maxColor);
  41323. maxColor = Math.max(b, maxColor);
  41324. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41325. if (tempData) {
  41326. tempData[pixelStorageIndex + 0] = r;
  41327. tempData[pixelStorageIndex + 1] = g;
  41328. tempData[pixelStorageIndex + 2] = b;
  41329. }
  41330. pixelIndexSlice++;
  41331. if (pixelIndexSlice % size == 0) {
  41332. pixelIndexH++;
  41333. pixelIndexSlice = 0;
  41334. if (pixelIndexH % size == 0) {
  41335. pixelIndexW++;
  41336. pixelIndexH = 0;
  41337. }
  41338. }
  41339. }
  41340. }
  41341. if (tempData && data) {
  41342. for (var i = 0; i < tempData.length; i++) {
  41343. if (i > 0 && (i + 1) % 4 === 0) {
  41344. data[i] = 255;
  41345. }
  41346. else {
  41347. var value = tempData[i];
  41348. data[i] = (value / maxColor * 255);
  41349. }
  41350. }
  41351. }
  41352. if (texture.is3D) {
  41353. texture.updateSize(size, size, size);
  41354. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41355. }
  41356. else {
  41357. texture.updateSize(size * size, size);
  41358. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41359. }
  41360. };
  41361. var scene = this.getScene();
  41362. if (scene) {
  41363. scene._loadFile(this.url, callback);
  41364. }
  41365. else {
  41366. this._engine._loadFile(this.url, callback);
  41367. }
  41368. return this._texture;
  41369. };
  41370. /**
  41371. * Starts the loading process of the texture.
  41372. */
  41373. ColorGradingTexture.prototype.loadTexture = function () {
  41374. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41375. this.load3dlTexture();
  41376. }
  41377. };
  41378. /**
  41379. * Clones the color gradind texture.
  41380. */
  41381. ColorGradingTexture.prototype.clone = function () {
  41382. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41383. // Base texture
  41384. newTexture.level = this.level;
  41385. return newTexture;
  41386. };
  41387. /**
  41388. * Called during delayed load for textures.
  41389. */
  41390. ColorGradingTexture.prototype.delayLoad = function () {
  41391. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41392. return;
  41393. }
  41394. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41395. this._texture = this._getFromCache(this.url, true);
  41396. if (!this._texture) {
  41397. this.loadTexture();
  41398. }
  41399. };
  41400. /**
  41401. * Parses a color grading texture serialized by Babylon.
  41402. * @param parsedTexture The texture information being parsedTexture
  41403. * @param scene The scene to load the texture in
  41404. * @param rootUrl The root url of the data assets to load
  41405. * @return A color gradind texture
  41406. */
  41407. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41408. var texture = null;
  41409. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41410. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41411. texture.name = parsedTexture.name;
  41412. texture.level = parsedTexture.level;
  41413. }
  41414. return texture;
  41415. };
  41416. /**
  41417. * Serializes the LUT texture to json format.
  41418. */
  41419. ColorGradingTexture.prototype.serialize = function () {
  41420. if (!this.name) {
  41421. return null;
  41422. }
  41423. var serializationObject = {};
  41424. serializationObject.name = this.name;
  41425. serializationObject.level = this.level;
  41426. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41427. return serializationObject;
  41428. };
  41429. /**
  41430. * Empty line regex stored for GC.
  41431. */
  41432. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41433. return ColorGradingTexture;
  41434. }(BABYLON.BaseTexture));
  41435. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41436. })(BABYLON || (BABYLON = {}));
  41437. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41438. var BABYLON;
  41439. (function (BABYLON) {
  41440. /**
  41441. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41442. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41443. * 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;
  41444. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41445. */
  41446. var ColorCurves = /** @class */ (function () {
  41447. function ColorCurves() {
  41448. this._dirty = true;
  41449. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41450. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41451. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41452. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41453. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41454. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41455. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41456. this._globalHue = 30;
  41457. this._globalDensity = 0;
  41458. this._globalSaturation = 0;
  41459. this._globalExposure = 0;
  41460. this._highlightsHue = 30;
  41461. this._highlightsDensity = 0;
  41462. this._highlightsSaturation = 0;
  41463. this._highlightsExposure = 0;
  41464. this._midtonesHue = 30;
  41465. this._midtonesDensity = 0;
  41466. this._midtonesSaturation = 0;
  41467. this._midtonesExposure = 0;
  41468. this._shadowsHue = 30;
  41469. this._shadowsDensity = 0;
  41470. this._shadowsSaturation = 0;
  41471. this._shadowsExposure = 0;
  41472. }
  41473. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41474. /**
  41475. * Gets the global Hue value.
  41476. * 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).
  41477. */
  41478. get: function () {
  41479. return this._globalHue;
  41480. },
  41481. /**
  41482. * Sets the global Hue value.
  41483. * 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).
  41484. */
  41485. set: function (value) {
  41486. this._globalHue = value;
  41487. this._dirty = true;
  41488. },
  41489. enumerable: true,
  41490. configurable: true
  41491. });
  41492. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41493. /**
  41494. * Gets the global Density value.
  41495. * 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.
  41496. * Values less than zero provide a filter of opposite hue.
  41497. */
  41498. get: function () {
  41499. return this._globalDensity;
  41500. },
  41501. /**
  41502. * Sets the global Density value.
  41503. * 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.
  41504. * Values less than zero provide a filter of opposite hue.
  41505. */
  41506. set: function (value) {
  41507. this._globalDensity = value;
  41508. this._dirty = true;
  41509. },
  41510. enumerable: true,
  41511. configurable: true
  41512. });
  41513. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41514. /**
  41515. * Gets the global Saturation value.
  41516. * 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.
  41517. */
  41518. get: function () {
  41519. return this._globalSaturation;
  41520. },
  41521. /**
  41522. * Sets the global Saturation value.
  41523. * 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.
  41524. */
  41525. set: function (value) {
  41526. this._globalSaturation = value;
  41527. this._dirty = true;
  41528. },
  41529. enumerable: true,
  41530. configurable: true
  41531. });
  41532. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41533. /**
  41534. * Gets the highlights Hue value.
  41535. * 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).
  41536. */
  41537. get: function () {
  41538. return this._highlightsHue;
  41539. },
  41540. /**
  41541. * Sets the highlights Hue value.
  41542. * 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).
  41543. */
  41544. set: function (value) {
  41545. this._highlightsHue = value;
  41546. this._dirty = true;
  41547. },
  41548. enumerable: true,
  41549. configurable: true
  41550. });
  41551. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41552. /**
  41553. * Gets the highlights Density value.
  41554. * 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.
  41555. * Values less than zero provide a filter of opposite hue.
  41556. */
  41557. get: function () {
  41558. return this._highlightsDensity;
  41559. },
  41560. /**
  41561. * Sets the highlights Density value.
  41562. * 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.
  41563. * Values less than zero provide a filter of opposite hue.
  41564. */
  41565. set: function (value) {
  41566. this._highlightsDensity = value;
  41567. this._dirty = true;
  41568. },
  41569. enumerable: true,
  41570. configurable: true
  41571. });
  41572. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41573. /**
  41574. * Gets the highlights Saturation value.
  41575. * 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.
  41576. */
  41577. get: function () {
  41578. return this._highlightsSaturation;
  41579. },
  41580. /**
  41581. * Sets the highlights Saturation value.
  41582. * 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.
  41583. */
  41584. set: function (value) {
  41585. this._highlightsSaturation = value;
  41586. this._dirty = true;
  41587. },
  41588. enumerable: true,
  41589. configurable: true
  41590. });
  41591. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41592. /**
  41593. * Gets the highlights Exposure value.
  41594. * 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.
  41595. */
  41596. get: function () {
  41597. return this._highlightsExposure;
  41598. },
  41599. /**
  41600. * Sets the highlights Exposure value.
  41601. * 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.
  41602. */
  41603. set: function (value) {
  41604. this._highlightsExposure = value;
  41605. this._dirty = true;
  41606. },
  41607. enumerable: true,
  41608. configurable: true
  41609. });
  41610. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41611. /**
  41612. * Gets the midtones Hue value.
  41613. * 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).
  41614. */
  41615. get: function () {
  41616. return this._midtonesHue;
  41617. },
  41618. /**
  41619. * Sets the midtones Hue value.
  41620. * 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).
  41621. */
  41622. set: function (value) {
  41623. this._midtonesHue = value;
  41624. this._dirty = true;
  41625. },
  41626. enumerable: true,
  41627. configurable: true
  41628. });
  41629. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41630. /**
  41631. * Gets the midtones Density value.
  41632. * 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.
  41633. * Values less than zero provide a filter of opposite hue.
  41634. */
  41635. get: function () {
  41636. return this._midtonesDensity;
  41637. },
  41638. /**
  41639. * Sets the midtones Density value.
  41640. * 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.
  41641. * Values less than zero provide a filter of opposite hue.
  41642. */
  41643. set: function (value) {
  41644. this._midtonesDensity = value;
  41645. this._dirty = true;
  41646. },
  41647. enumerable: true,
  41648. configurable: true
  41649. });
  41650. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41651. /**
  41652. * Gets the midtones Saturation value.
  41653. * 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.
  41654. */
  41655. get: function () {
  41656. return this._midtonesSaturation;
  41657. },
  41658. /**
  41659. * Sets the midtones Saturation value.
  41660. * 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.
  41661. */
  41662. set: function (value) {
  41663. this._midtonesSaturation = value;
  41664. this._dirty = true;
  41665. },
  41666. enumerable: true,
  41667. configurable: true
  41668. });
  41669. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41670. /**
  41671. * Gets the midtones Exposure value.
  41672. * 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.
  41673. */
  41674. get: function () {
  41675. return this._midtonesExposure;
  41676. },
  41677. /**
  41678. * Sets the midtones Exposure value.
  41679. * 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.
  41680. */
  41681. set: function (value) {
  41682. this._midtonesExposure = value;
  41683. this._dirty = true;
  41684. },
  41685. enumerable: true,
  41686. configurable: true
  41687. });
  41688. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41689. /**
  41690. * Gets the shadows Hue value.
  41691. * 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).
  41692. */
  41693. get: function () {
  41694. return this._shadowsHue;
  41695. },
  41696. /**
  41697. * Sets the shadows Hue value.
  41698. * 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).
  41699. */
  41700. set: function (value) {
  41701. this._shadowsHue = value;
  41702. this._dirty = true;
  41703. },
  41704. enumerable: true,
  41705. configurable: true
  41706. });
  41707. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41708. /**
  41709. * Gets the shadows Density value.
  41710. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  41711. * Values less than zero provide a filter of opposite hue.
  41712. */
  41713. get: function () {
  41714. return this._shadowsDensity;
  41715. },
  41716. /**
  41717. * Sets the shadows Density value.
  41718. * 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.
  41719. * Values less than zero provide a filter of opposite hue.
  41720. */
  41721. set: function (value) {
  41722. this._shadowsDensity = value;
  41723. this._dirty = true;
  41724. },
  41725. enumerable: true,
  41726. configurable: true
  41727. });
  41728. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41729. /**
  41730. * Gets the shadows Saturation value.
  41731. * 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.
  41732. */
  41733. get: function () {
  41734. return this._shadowsSaturation;
  41735. },
  41736. /**
  41737. * Sets the shadows Saturation value.
  41738. * 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.
  41739. */
  41740. set: function (value) {
  41741. this._shadowsSaturation = value;
  41742. this._dirty = true;
  41743. },
  41744. enumerable: true,
  41745. configurable: true
  41746. });
  41747. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41748. /**
  41749. * Gets the shadows Exposure value.
  41750. * 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.
  41751. */
  41752. get: function () {
  41753. return this._shadowsExposure;
  41754. },
  41755. /**
  41756. * Sets the shadows Exposure value.
  41757. * 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.
  41758. */
  41759. set: function (value) {
  41760. this._shadowsExposure = value;
  41761. this._dirty = true;
  41762. },
  41763. enumerable: true,
  41764. configurable: true
  41765. });
  41766. ColorCurves.prototype.getClassName = function () {
  41767. return "ColorCurves";
  41768. };
  41769. /**
  41770. * Binds the color curves to the shader.
  41771. * @param colorCurves The color curve to bind
  41772. * @param effect The effect to bind to
  41773. */
  41774. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41775. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41776. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41777. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41778. if (colorCurves._dirty) {
  41779. colorCurves._dirty = false;
  41780. // Fill in global info.
  41781. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41782. // Compute highlights info.
  41783. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41784. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41785. // Compute midtones info.
  41786. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41787. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41788. // Compute shadows info.
  41789. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41790. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41791. // Compute deltas (neutral is midtones).
  41792. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41793. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41794. }
  41795. if (effect) {
  41796. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41797. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41798. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41799. }
  41800. };
  41801. /**
  41802. * Prepare the list of uniforms associated with the ColorCurves effects.
  41803. * @param uniformsList The list of uniforms used in the effect
  41804. */
  41805. ColorCurves.PrepareUniforms = function (uniformsList) {
  41806. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41807. };
  41808. /**
  41809. * Returns color grading data based on a hue, density, saturation and exposure value.
  41810. * @param filterHue The hue of the color filter.
  41811. * @param filterDensity The density of the color filter.
  41812. * @param saturation The saturation.
  41813. * @param exposure The exposure.
  41814. * @param result The result data container.
  41815. */
  41816. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41817. if (hue == null) {
  41818. return;
  41819. }
  41820. hue = ColorCurves.clamp(hue, 0, 360);
  41821. density = ColorCurves.clamp(density, -100, 100);
  41822. saturation = ColorCurves.clamp(saturation, -100, 100);
  41823. exposure = ColorCurves.clamp(exposure, -100, 100);
  41824. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41825. // so that the maximum filter density is only 50% control. This provides fine control
  41826. // for small values and reasonable range.
  41827. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41828. density *= 0.5;
  41829. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41830. if (density < 0) {
  41831. density *= -1;
  41832. hue = (hue + 180) % 360;
  41833. }
  41834. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41835. result.scaleToRef(2, result);
  41836. result.a = 1 + 0.01 * saturation;
  41837. };
  41838. /**
  41839. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41840. * @param value The input slider value in range [-100,100].
  41841. * @returns Adjusted value.
  41842. */
  41843. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41844. value /= 100;
  41845. var x = Math.abs(value);
  41846. x = Math.pow(x, 2);
  41847. if (value < 0) {
  41848. x *= -1;
  41849. }
  41850. x *= 100;
  41851. return x;
  41852. };
  41853. /**
  41854. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41855. * @param hue The hue (H) input.
  41856. * @param saturation The saturation (S) input.
  41857. * @param brightness The brightness (B) input.
  41858. * @result An RGBA color represented as Vector4.
  41859. */
  41860. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41861. var h = ColorCurves.clamp(hue, 0, 360);
  41862. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41863. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41864. if (s === 0) {
  41865. result.r = v;
  41866. result.g = v;
  41867. result.b = v;
  41868. }
  41869. else {
  41870. // sector 0 to 5
  41871. h /= 60;
  41872. var i = Math.floor(h);
  41873. // fractional part of h
  41874. var f = h - i;
  41875. var p = v * (1 - s);
  41876. var q = v * (1 - s * f);
  41877. var t = v * (1 - s * (1 - f));
  41878. switch (i) {
  41879. case 0:
  41880. result.r = v;
  41881. result.g = t;
  41882. result.b = p;
  41883. break;
  41884. case 1:
  41885. result.r = q;
  41886. result.g = v;
  41887. result.b = p;
  41888. break;
  41889. case 2:
  41890. result.r = p;
  41891. result.g = v;
  41892. result.b = t;
  41893. break;
  41894. case 3:
  41895. result.r = p;
  41896. result.g = q;
  41897. result.b = v;
  41898. break;
  41899. case 4:
  41900. result.r = t;
  41901. result.g = p;
  41902. result.b = v;
  41903. break;
  41904. default: // case 5:
  41905. result.r = v;
  41906. result.g = p;
  41907. result.b = q;
  41908. break;
  41909. }
  41910. }
  41911. result.a = 1;
  41912. };
  41913. /**
  41914. * Returns a value clamped between min and max
  41915. * @param value The value to clamp
  41916. * @param min The minimum of value
  41917. * @param max The maximum of value
  41918. * @returns The clamped value.
  41919. */
  41920. ColorCurves.clamp = function (value, min, max) {
  41921. return Math.min(Math.max(value, min), max);
  41922. };
  41923. /**
  41924. * Clones the current color curve instance.
  41925. * @return The cloned curves
  41926. */
  41927. ColorCurves.prototype.clone = function () {
  41928. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41929. };
  41930. /**
  41931. * Serializes the current color curve instance to a json representation.
  41932. * @return a JSON representation
  41933. */
  41934. ColorCurves.prototype.serialize = function () {
  41935. return BABYLON.SerializationHelper.Serialize(this);
  41936. };
  41937. /**
  41938. * Parses the color curve from a json representation.
  41939. * @param source the JSON source to parse
  41940. * @return The parsed curves
  41941. */
  41942. ColorCurves.Parse = function (source) {
  41943. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41944. };
  41945. __decorate([
  41946. BABYLON.serialize()
  41947. ], ColorCurves.prototype, "_globalHue", void 0);
  41948. __decorate([
  41949. BABYLON.serialize()
  41950. ], ColorCurves.prototype, "_globalDensity", void 0);
  41951. __decorate([
  41952. BABYLON.serialize()
  41953. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41954. __decorate([
  41955. BABYLON.serialize()
  41956. ], ColorCurves.prototype, "_globalExposure", void 0);
  41957. __decorate([
  41958. BABYLON.serialize()
  41959. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41960. __decorate([
  41961. BABYLON.serialize()
  41962. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41963. __decorate([
  41964. BABYLON.serialize()
  41965. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41966. __decorate([
  41967. BABYLON.serialize()
  41968. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41969. __decorate([
  41970. BABYLON.serialize()
  41971. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41972. __decorate([
  41973. BABYLON.serialize()
  41974. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41975. __decorate([
  41976. BABYLON.serialize()
  41977. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41978. __decorate([
  41979. BABYLON.serialize()
  41980. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41981. return ColorCurves;
  41982. }());
  41983. BABYLON.ColorCurves = ColorCurves;
  41984. })(BABYLON || (BABYLON = {}));
  41985. //# sourceMappingURL=babylon.colorCurves.js.map
  41986. //# sourceMappingURL=babylon.behavior.js.map
  41987. var BABYLON;
  41988. (function (BABYLON) {
  41989. /**
  41990. * "Static Class" containing the most commonly used helper while dealing with material for
  41991. * rendering purpose.
  41992. *
  41993. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41994. *
  41995. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41996. */
  41997. var MaterialHelper = /** @class */ (function () {
  41998. function MaterialHelper() {
  41999. }
  42000. /**
  42001. * Bind the current view position to an effect.
  42002. * @param effect The effect to be bound
  42003. * @param scene The scene the eyes position is used from
  42004. */
  42005. MaterialHelper.BindEyePosition = function (effect, scene) {
  42006. if (scene._forcedViewPosition) {
  42007. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42008. return;
  42009. }
  42010. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42011. };
  42012. /**
  42013. * Helps preparing the defines values about the UVs in used in the effect.
  42014. * UVs are shared as much as we can accross chanels in the shaders.
  42015. * @param texture The texture we are preparing the UVs for
  42016. * @param defines The defines to update
  42017. * @param key The chanel key "diffuse", "specular"... used in the shader
  42018. */
  42019. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42020. defines._needUVs = true;
  42021. defines[key] = true;
  42022. if (texture.getTextureMatrix().isIdentity(true)) {
  42023. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42024. if (texture.coordinatesIndex === 0) {
  42025. defines["MAINUV1"] = true;
  42026. }
  42027. else {
  42028. defines["MAINUV2"] = true;
  42029. }
  42030. }
  42031. else {
  42032. defines[key + "DIRECTUV"] = 0;
  42033. }
  42034. };
  42035. /**
  42036. * Binds a texture matrix value to its corrsponding uniform
  42037. * @param texture The texture to bind the matrix for
  42038. * @param uniformBuffer The uniform buffer receivin the data
  42039. * @param key The chanel key "diffuse", "specular"... used in the shader
  42040. */
  42041. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42042. var matrix = texture.getTextureMatrix();
  42043. if (!matrix.isIdentity(true)) {
  42044. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42045. }
  42046. };
  42047. /**
  42048. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42049. * @param mesh defines the current mesh
  42050. * @param scene defines the current scene
  42051. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42052. * @param pointsCloud defines if point cloud rendering has to be turned on
  42053. * @param fogEnabled defines if fog has to be turned on
  42054. * @param alphaTest defines if alpha testing has to be turned on
  42055. * @param defines defines the current list of defines
  42056. */
  42057. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42058. if (defines._areMiscDirty) {
  42059. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42060. defines["POINTSIZE"] = pointsCloud;
  42061. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42062. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42063. defines["ALPHATEST"] = alphaTest;
  42064. }
  42065. };
  42066. /**
  42067. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42068. * @param scene defines the current scene
  42069. * @param engine defines the current engine
  42070. * @param defines specifies the list of active defines
  42071. * @param useInstances defines if instances have to be turned on
  42072. * @param useClipPlane defines if clip plane have to be turned on
  42073. */
  42074. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42075. if (useClipPlane === void 0) { useClipPlane = null; }
  42076. var changed = false;
  42077. if (useClipPlane == null) {
  42078. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42079. }
  42080. if (defines["CLIPPLANE"] !== useClipPlane) {
  42081. defines["CLIPPLANE"] = useClipPlane;
  42082. changed = true;
  42083. }
  42084. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42085. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42086. changed = true;
  42087. }
  42088. if (defines["INSTANCES"] !== useInstances) {
  42089. defines["INSTANCES"] = useInstances;
  42090. changed = true;
  42091. }
  42092. if (changed) {
  42093. defines.markAsUnprocessed();
  42094. }
  42095. };
  42096. /**
  42097. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42098. * @param mesh The mesh containing the geometry data we will draw
  42099. * @param defines The defines to update
  42100. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42101. * @param useBones Precise whether bones should be used or not (override mesh info)
  42102. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42103. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42104. * @returns false if defines are considered not dirty and have not been checked
  42105. */
  42106. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42107. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42108. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42109. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42110. return false;
  42111. }
  42112. defines._normals = defines._needNormals;
  42113. defines._uvs = defines._needUVs;
  42114. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42115. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42116. defines["TANGENT"] = true;
  42117. }
  42118. if (defines._needUVs) {
  42119. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42120. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42121. }
  42122. else {
  42123. defines["UV1"] = false;
  42124. defines["UV2"] = false;
  42125. }
  42126. if (useVertexColor) {
  42127. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42128. defines["VERTEXCOLOR"] = hasVertexColors;
  42129. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42130. }
  42131. if (useBones) {
  42132. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42133. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42134. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42135. }
  42136. else {
  42137. defines["NUM_BONE_INFLUENCERS"] = 0;
  42138. defines["BonesPerMesh"] = 0;
  42139. }
  42140. }
  42141. if (useMorphTargets) {
  42142. var manager = mesh.morphTargetManager;
  42143. if (manager) {
  42144. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42145. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42146. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42147. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42148. }
  42149. else {
  42150. defines["MORPHTARGETS_TANGENT"] = false;
  42151. defines["MORPHTARGETS_NORMAL"] = false;
  42152. defines["MORPHTARGETS"] = false;
  42153. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42154. }
  42155. }
  42156. return true;
  42157. };
  42158. /**
  42159. * Prepares the defines related to the light information passed in parameter
  42160. * @param scene The scene we are intending to draw
  42161. * @param mesh The mesh the effect is compiling for
  42162. * @param defines The defines to update
  42163. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42164. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42165. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42166. * @returns true if normals will be required for the rest of the effect
  42167. */
  42168. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42169. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42170. if (disableLighting === void 0) { disableLighting = false; }
  42171. if (!defines._areLightsDirty) {
  42172. return defines._needNormals;
  42173. }
  42174. var lightIndex = 0;
  42175. var needNormals = false;
  42176. var needRebuild = false;
  42177. var lightmapMode = false;
  42178. var shadowEnabled = false;
  42179. var specularEnabled = false;
  42180. if (scene.lightsEnabled && !disableLighting) {
  42181. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42182. var light = _a[_i];
  42183. needNormals = true;
  42184. if (defines["LIGHT" + lightIndex] === undefined) {
  42185. needRebuild = true;
  42186. }
  42187. defines["LIGHT" + lightIndex] = true;
  42188. defines["SPOTLIGHT" + lightIndex] = false;
  42189. defines["HEMILIGHT" + lightIndex] = false;
  42190. defines["POINTLIGHT" + lightIndex] = false;
  42191. defines["DIRLIGHT" + lightIndex] = false;
  42192. var type;
  42193. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42194. type = "SPOTLIGHT" + lightIndex;
  42195. var spotLight = light;
  42196. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42197. }
  42198. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42199. type = "HEMILIGHT" + lightIndex;
  42200. }
  42201. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42202. type = "POINTLIGHT" + lightIndex;
  42203. }
  42204. else {
  42205. type = "DIRLIGHT" + lightIndex;
  42206. }
  42207. defines[type] = true;
  42208. // Specular
  42209. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42210. specularEnabled = true;
  42211. }
  42212. // Shadows
  42213. defines["SHADOW" + lightIndex] = false;
  42214. defines["SHADOWPCF" + lightIndex] = false;
  42215. defines["SHADOWPCSS" + lightIndex] = false;
  42216. defines["SHADOWPOISSON" + lightIndex] = false;
  42217. defines["SHADOWESM" + lightIndex] = false;
  42218. defines["SHADOWCUBE" + lightIndex] = false;
  42219. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42220. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42221. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42222. var shadowGenerator = light.getShadowGenerator();
  42223. if (shadowGenerator) {
  42224. shadowEnabled = true;
  42225. shadowGenerator.prepareDefines(defines, lightIndex);
  42226. }
  42227. }
  42228. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42229. lightmapMode = true;
  42230. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42231. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42232. }
  42233. else {
  42234. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42235. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42236. }
  42237. lightIndex++;
  42238. if (lightIndex === maxSimultaneousLights)
  42239. break;
  42240. }
  42241. }
  42242. defines["SPECULARTERM"] = specularEnabled;
  42243. defines["SHADOWS"] = shadowEnabled;
  42244. // Resetting all other lights if any
  42245. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42246. if (defines["LIGHT" + index] !== undefined) {
  42247. defines["LIGHT" + index] = false;
  42248. defines["HEMILIGHT" + lightIndex] = false;
  42249. defines["POINTLIGHT" + lightIndex] = false;
  42250. defines["DIRLIGHT" + lightIndex] = false;
  42251. defines["SPOTLIGHT" + lightIndex] = false;
  42252. defines["SHADOW" + lightIndex] = false;
  42253. }
  42254. }
  42255. var caps = scene.getEngine().getCaps();
  42256. if (defines["SHADOWFLOAT"] === undefined) {
  42257. needRebuild = true;
  42258. }
  42259. defines["SHADOWFLOAT"] = shadowEnabled &&
  42260. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42261. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42262. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42263. if (needRebuild) {
  42264. defines.rebuild();
  42265. }
  42266. return needNormals;
  42267. };
  42268. /**
  42269. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42270. * that won t be acctive due to defines being turned off.
  42271. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42272. * @param samplersList The samplers list
  42273. * @param defines The defines helping in the list generation
  42274. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42275. */
  42276. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42277. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42278. var uniformsList;
  42279. var uniformBuffersList = null;
  42280. if (uniformsListOrOptions.uniformsNames) {
  42281. var options = uniformsListOrOptions;
  42282. uniformsList = options.uniformsNames;
  42283. uniformBuffersList = options.uniformBuffersNames;
  42284. samplersList = options.samplers;
  42285. defines = options.defines;
  42286. maxSimultaneousLights = options.maxSimultaneousLights;
  42287. }
  42288. else {
  42289. uniformsList = uniformsListOrOptions;
  42290. if (!samplersList) {
  42291. samplersList = [];
  42292. }
  42293. }
  42294. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42295. if (!defines["LIGHT" + lightIndex]) {
  42296. break;
  42297. }
  42298. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42299. if (uniformBuffersList) {
  42300. uniformBuffersList.push("Light" + lightIndex);
  42301. }
  42302. samplersList.push("shadowSampler" + lightIndex);
  42303. samplersList.push("depthSampler" + lightIndex);
  42304. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42305. samplersList.push("projectionLightSampler" + lightIndex);
  42306. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42307. }
  42308. }
  42309. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42310. uniformsList.push("morphTargetInfluences");
  42311. }
  42312. };
  42313. /**
  42314. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42315. * @param defines The defines to update while falling back
  42316. * @param fallbacks The authorized effect fallbacks
  42317. * @param maxSimultaneousLights The maximum number of lights allowed
  42318. * @param rank the current rank of the Effect
  42319. * @returns The newly affected rank
  42320. */
  42321. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42322. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42323. if (rank === void 0) { rank = 0; }
  42324. var lightFallbackRank = 0;
  42325. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42326. if (!defines["LIGHT" + lightIndex]) {
  42327. break;
  42328. }
  42329. if (lightIndex > 0) {
  42330. lightFallbackRank = rank + lightIndex;
  42331. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42332. }
  42333. if (!defines["SHADOWS"]) {
  42334. if (defines["SHADOW" + lightIndex]) {
  42335. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42336. }
  42337. if (defines["SHADOWPCF" + lightIndex]) {
  42338. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42339. }
  42340. if (defines["SHADOWPCSS" + lightIndex]) {
  42341. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42342. }
  42343. if (defines["SHADOWPOISSON" + lightIndex]) {
  42344. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42345. }
  42346. if (defines["SHADOWESM" + lightIndex]) {
  42347. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42348. }
  42349. }
  42350. }
  42351. return lightFallbackRank++;
  42352. };
  42353. /**
  42354. * Prepares the list of attributes required for morph targets according to the effect defines.
  42355. * @param attribs The current list of supported attribs
  42356. * @param mesh The mesh to prepare the morph targets attributes for
  42357. * @param defines The current Defines of the effect
  42358. */
  42359. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42360. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42361. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42362. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42363. var manager = mesh.morphTargetManager;
  42364. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42365. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42366. for (var index = 0; index < influencers; index++) {
  42367. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42368. if (normal) {
  42369. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42370. }
  42371. if (tangent) {
  42372. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42373. }
  42374. if (attribs.length > maxAttributesCount) {
  42375. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42376. }
  42377. }
  42378. }
  42379. };
  42380. /**
  42381. * Prepares the list of attributes required for bones according to the effect defines.
  42382. * @param attribs The current list of supported attribs
  42383. * @param mesh The mesh to prepare the bones attributes for
  42384. * @param defines The current Defines of the effect
  42385. * @param fallbacks The current efffect fallback strategy
  42386. */
  42387. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42388. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42389. fallbacks.addCPUSkinningFallback(0, mesh);
  42390. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42391. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42392. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42393. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42394. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42395. }
  42396. }
  42397. };
  42398. /**
  42399. * Prepares the list of attributes required for instances according to the effect defines.
  42400. * @param attribs The current list of supported attribs
  42401. * @param defines The current Defines of the effect
  42402. */
  42403. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42404. if (defines["INSTANCES"]) {
  42405. attribs.push("world0");
  42406. attribs.push("world1");
  42407. attribs.push("world2");
  42408. attribs.push("world3");
  42409. }
  42410. };
  42411. /**
  42412. * Binds the light shadow information to the effect for the given mesh.
  42413. * @param light The light containing the generator
  42414. * @param scene The scene the lights belongs to
  42415. * @param mesh The mesh we are binding the information to render
  42416. * @param lightIndex The light index in the effect used to render the mesh
  42417. * @param effect The effect we are binding the data to
  42418. */
  42419. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42420. if (light.shadowEnabled && mesh.receiveShadows) {
  42421. var shadowGenerator = light.getShadowGenerator();
  42422. if (shadowGenerator) {
  42423. shadowGenerator.bindShadowLight(lightIndex, effect);
  42424. }
  42425. }
  42426. };
  42427. /**
  42428. * Binds the light information to the effect.
  42429. * @param light The light containing the generator
  42430. * @param effect The effect we are binding the data to
  42431. * @param lightIndex The light index in the effect used to render
  42432. */
  42433. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42434. light.transferToEffect(effect, lightIndex + "");
  42435. };
  42436. /**
  42437. * Binds the lights information from the scene to the effect for the given mesh.
  42438. * @param scene The scene the lights belongs to
  42439. * @param mesh The mesh we are binding the information to render
  42440. * @param effect The effect we are binding the data to
  42441. * @param defines The generated defines for the effect
  42442. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42443. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42444. */
  42445. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42446. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42447. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42448. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42449. for (var i = 0; i < len; i++) {
  42450. var light = mesh._lightSources[i];
  42451. var iAsString = i.toString();
  42452. var scaledIntensity = light.getScaledIntensity();
  42453. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42454. MaterialHelper.BindLightProperties(light, effect, i);
  42455. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42456. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42457. if (defines["SPECULARTERM"]) {
  42458. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42459. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42460. }
  42461. // Shadows
  42462. if (scene.shadowsEnabled) {
  42463. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42464. }
  42465. light._uniformBuffer.update();
  42466. }
  42467. };
  42468. /**
  42469. * Binds the fog information from the scene to the effect for the given mesh.
  42470. * @param scene The scene the lights belongs to
  42471. * @param mesh The mesh we are binding the information to render
  42472. * @param effect The effect we are binding the data to
  42473. */
  42474. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42475. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42476. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42477. effect.setColor3("vFogColor", scene.fogColor);
  42478. }
  42479. };
  42480. /**
  42481. * Binds the bones information from the mesh to the effect.
  42482. * @param mesh The mesh we are binding the information to render
  42483. * @param effect The effect we are binding the data to
  42484. */
  42485. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42486. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42487. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42488. if (matrices && effect) {
  42489. effect.setMatrices("mBones", matrices);
  42490. }
  42491. }
  42492. };
  42493. /**
  42494. * Binds the morph targets information from the mesh to the effect.
  42495. * @param abstractMesh The mesh we are binding the information to render
  42496. * @param effect The effect we are binding the data to
  42497. */
  42498. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42499. var manager = abstractMesh.morphTargetManager;
  42500. if (!abstractMesh || !manager) {
  42501. return;
  42502. }
  42503. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42504. };
  42505. /**
  42506. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42507. * @param defines The generated defines used in the effect
  42508. * @param effect The effect we are binding the data to
  42509. * @param scene The scene we are willing to render with logarithmic scale for
  42510. */
  42511. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42512. if (defines["LOGARITHMICDEPTH"]) {
  42513. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42514. }
  42515. };
  42516. /**
  42517. * Binds the clip plane information from the scene to the effect.
  42518. * @param scene The scene the clip plane information are extracted from
  42519. * @param effect The effect we are binding the data to
  42520. */
  42521. MaterialHelper.BindClipPlane = function (effect, scene) {
  42522. if (scene.clipPlane) {
  42523. var clipPlane = scene.clipPlane;
  42524. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42525. }
  42526. };
  42527. return MaterialHelper;
  42528. }());
  42529. BABYLON.MaterialHelper = MaterialHelper;
  42530. })(BABYLON || (BABYLON = {}));
  42531. //# sourceMappingURL=babylon.materialHelper.js.map
  42532. var BABYLON;
  42533. (function (BABYLON) {
  42534. var PushMaterial = /** @class */ (function (_super) {
  42535. __extends(PushMaterial, _super);
  42536. function PushMaterial(name, scene) {
  42537. var _this = _super.call(this, name, scene) || this;
  42538. _this._normalMatrix = new BABYLON.Matrix();
  42539. _this.storeEffectOnSubMeshes = true;
  42540. return _this;
  42541. }
  42542. PushMaterial.prototype.getEffect = function () {
  42543. return this._activeEffect;
  42544. };
  42545. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42546. if (!mesh) {
  42547. return false;
  42548. }
  42549. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42550. return true;
  42551. }
  42552. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42553. };
  42554. /**
  42555. * Binds the given world matrix to the active effect
  42556. *
  42557. * @param world the matrix to bind
  42558. */
  42559. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42560. this._activeEffect.setMatrix("world", world);
  42561. };
  42562. /**
  42563. * Binds the given normal matrix to the active effect
  42564. *
  42565. * @param normalMatrix the matrix to bind
  42566. */
  42567. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42568. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42569. };
  42570. PushMaterial.prototype.bind = function (world, mesh) {
  42571. if (!mesh) {
  42572. return;
  42573. }
  42574. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42575. };
  42576. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42577. if (effect === void 0) { effect = null; }
  42578. _super.prototype._afterBind.call(this, mesh);
  42579. this.getScene()._cachedEffect = effect;
  42580. };
  42581. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42582. if (visibility === void 0) { visibility = 1; }
  42583. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42584. };
  42585. return PushMaterial;
  42586. }(BABYLON.Material));
  42587. BABYLON.PushMaterial = PushMaterial;
  42588. })(BABYLON || (BABYLON = {}));
  42589. //# sourceMappingURL=babylon.pushMaterial.js.map
  42590. var BABYLON;
  42591. (function (BABYLON) {
  42592. /** @hidden */
  42593. var StandardMaterialDefines = /** @class */ (function (_super) {
  42594. __extends(StandardMaterialDefines, _super);
  42595. function StandardMaterialDefines() {
  42596. var _this = _super.call(this) || this;
  42597. _this.MAINUV1 = false;
  42598. _this.MAINUV2 = false;
  42599. _this.DIFFUSE = false;
  42600. _this.DIFFUSEDIRECTUV = 0;
  42601. _this.AMBIENT = false;
  42602. _this.AMBIENTDIRECTUV = 0;
  42603. _this.OPACITY = false;
  42604. _this.OPACITYDIRECTUV = 0;
  42605. _this.OPACITYRGB = false;
  42606. _this.REFLECTION = false;
  42607. _this.EMISSIVE = false;
  42608. _this.EMISSIVEDIRECTUV = 0;
  42609. _this.SPECULAR = false;
  42610. _this.SPECULARDIRECTUV = 0;
  42611. _this.BUMP = false;
  42612. _this.BUMPDIRECTUV = 0;
  42613. _this.PARALLAX = false;
  42614. _this.PARALLAXOCCLUSION = false;
  42615. _this.SPECULAROVERALPHA = false;
  42616. _this.CLIPPLANE = false;
  42617. _this.ALPHATEST = false;
  42618. _this.DEPTHPREPASS = false;
  42619. _this.ALPHAFROMDIFFUSE = false;
  42620. _this.POINTSIZE = false;
  42621. _this.FOG = false;
  42622. _this.SPECULARTERM = false;
  42623. _this.DIFFUSEFRESNEL = false;
  42624. _this.OPACITYFRESNEL = false;
  42625. _this.REFLECTIONFRESNEL = false;
  42626. _this.REFRACTIONFRESNEL = false;
  42627. _this.EMISSIVEFRESNEL = false;
  42628. _this.FRESNEL = false;
  42629. _this.NORMAL = false;
  42630. _this.UV1 = false;
  42631. _this.UV2 = false;
  42632. _this.VERTEXCOLOR = false;
  42633. _this.VERTEXALPHA = false;
  42634. _this.NUM_BONE_INFLUENCERS = 0;
  42635. _this.BonesPerMesh = 0;
  42636. _this.INSTANCES = false;
  42637. _this.GLOSSINESS = false;
  42638. _this.ROUGHNESS = false;
  42639. _this.EMISSIVEASILLUMINATION = false;
  42640. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42641. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42642. _this.LIGHTMAP = false;
  42643. _this.LIGHTMAPDIRECTUV = 0;
  42644. _this.OBJECTSPACE_NORMALMAP = false;
  42645. _this.USELIGHTMAPASSHADOWMAP = false;
  42646. _this.REFLECTIONMAP_3D = false;
  42647. _this.REFLECTIONMAP_SPHERICAL = false;
  42648. _this.REFLECTIONMAP_PLANAR = false;
  42649. _this.REFLECTIONMAP_CUBIC = false;
  42650. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42651. _this.REFLECTIONMAP_PROJECTION = false;
  42652. _this.REFLECTIONMAP_SKYBOX = false;
  42653. _this.REFLECTIONMAP_EXPLICIT = false;
  42654. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42655. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42656. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42657. _this.INVERTCUBICMAP = false;
  42658. _this.LOGARITHMICDEPTH = false;
  42659. _this.REFRACTION = false;
  42660. _this.REFRACTIONMAP_3D = false;
  42661. _this.REFLECTIONOVERALPHA = false;
  42662. _this.TWOSIDEDLIGHTING = false;
  42663. _this.SHADOWFLOAT = false;
  42664. _this.MORPHTARGETS = false;
  42665. _this.MORPHTARGETS_NORMAL = false;
  42666. _this.MORPHTARGETS_TANGENT = false;
  42667. _this.NUM_MORPH_INFLUENCERS = 0;
  42668. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42669. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42670. _this.IMAGEPROCESSING = false;
  42671. _this.VIGNETTE = false;
  42672. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42673. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42674. _this.TONEMAPPING = false;
  42675. _this.CONTRAST = false;
  42676. _this.COLORCURVES = false;
  42677. _this.COLORGRADING = false;
  42678. _this.COLORGRADING3D = false;
  42679. _this.SAMPLER3DGREENDEPTH = false;
  42680. _this.SAMPLER3DBGRMAP = false;
  42681. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42682. /**
  42683. * If the reflection texture on this material is in linear color space
  42684. * @hidden
  42685. */
  42686. _this.IS_REFLECTION_LINEAR = false;
  42687. /**
  42688. * If the refraction texture on this material is in linear color space
  42689. * @hidden
  42690. */
  42691. _this.IS_REFRACTION_LINEAR = false;
  42692. _this.EXPOSURE = false;
  42693. _this.rebuild();
  42694. return _this;
  42695. }
  42696. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42697. var modes = [
  42698. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42699. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42700. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42701. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42702. ];
  42703. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42704. var mode = modes_1[_i];
  42705. this[mode] = (mode === modeToEnable);
  42706. }
  42707. };
  42708. return StandardMaterialDefines;
  42709. }(BABYLON.MaterialDefines));
  42710. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42711. var StandardMaterial = /** @class */ (function (_super) {
  42712. __extends(StandardMaterial, _super);
  42713. function StandardMaterial(name, scene) {
  42714. var _this = _super.call(this, name, scene) || this;
  42715. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42716. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42717. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42718. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42719. _this.specularPower = 64;
  42720. _this._useAlphaFromDiffuseTexture = false;
  42721. _this._useEmissiveAsIllumination = false;
  42722. _this._linkEmissiveWithDiffuse = false;
  42723. _this._useSpecularOverAlpha = false;
  42724. _this._useReflectionOverAlpha = false;
  42725. _this._disableLighting = false;
  42726. _this._useObjectSpaceNormalMap = false;
  42727. _this._useParallax = false;
  42728. _this._useParallaxOcclusion = false;
  42729. _this.parallaxScaleBias = 0.05;
  42730. _this._roughness = 0;
  42731. _this.indexOfRefraction = 0.98;
  42732. _this.invertRefractionY = true;
  42733. /**
  42734. * Defines the alpha limits in alpha test mode
  42735. */
  42736. _this.alphaCutOff = 0.4;
  42737. _this._useLightmapAsShadowmap = false;
  42738. _this._useReflectionFresnelFromSpecular = false;
  42739. _this._useGlossinessFromSpecularMapAlpha = false;
  42740. _this._maxSimultaneousLights = 4;
  42741. /**
  42742. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42743. */
  42744. _this._invertNormalMapX = false;
  42745. /**
  42746. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42747. */
  42748. _this._invertNormalMapY = false;
  42749. /**
  42750. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42751. */
  42752. _this._twoSidedLighting = false;
  42753. _this._renderTargets = new BABYLON.SmartArray(16);
  42754. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42755. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42756. // Setup the default processing configuration to the scene.
  42757. _this._attachImageProcessingConfiguration(null);
  42758. _this.getRenderTargetTextures = function () {
  42759. _this._renderTargets.reset();
  42760. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42761. _this._renderTargets.push(_this._reflectionTexture);
  42762. }
  42763. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42764. _this._renderTargets.push(_this._refractionTexture);
  42765. }
  42766. return _this._renderTargets;
  42767. };
  42768. return _this;
  42769. }
  42770. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42771. /**
  42772. * Gets the image processing configuration used either in this material.
  42773. */
  42774. get: function () {
  42775. return this._imageProcessingConfiguration;
  42776. },
  42777. /**
  42778. * Sets the Default image processing configuration used either in the this material.
  42779. *
  42780. * If sets to null, the scene one is in use.
  42781. */
  42782. set: function (value) {
  42783. this._attachImageProcessingConfiguration(value);
  42784. // Ensure the effect will be rebuilt.
  42785. this._markAllSubMeshesAsTexturesDirty();
  42786. },
  42787. enumerable: true,
  42788. configurable: true
  42789. });
  42790. /**
  42791. * Attaches a new image processing configuration to the Standard Material.
  42792. * @param configuration
  42793. */
  42794. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42795. var _this = this;
  42796. if (configuration === this._imageProcessingConfiguration) {
  42797. return;
  42798. }
  42799. // Detaches observer.
  42800. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42801. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42802. }
  42803. // Pick the scene configuration if needed.
  42804. if (!configuration) {
  42805. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42806. }
  42807. else {
  42808. this._imageProcessingConfiguration = configuration;
  42809. }
  42810. // Attaches observer.
  42811. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42812. _this._markAllSubMeshesAsImageProcessingDirty();
  42813. });
  42814. };
  42815. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42816. /**
  42817. * Gets wether the color curves effect is enabled.
  42818. */
  42819. get: function () {
  42820. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42821. },
  42822. /**
  42823. * Sets wether the color curves effect is enabled.
  42824. */
  42825. set: function (value) {
  42826. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42827. },
  42828. enumerable: true,
  42829. configurable: true
  42830. });
  42831. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42832. /**
  42833. * Gets wether the color grading effect is enabled.
  42834. */
  42835. get: function () {
  42836. return this.imageProcessingConfiguration.colorGradingEnabled;
  42837. },
  42838. /**
  42839. * Gets wether the color grading effect is enabled.
  42840. */
  42841. set: function (value) {
  42842. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42843. },
  42844. enumerable: true,
  42845. configurable: true
  42846. });
  42847. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42848. /**
  42849. * Gets wether tonemapping is enabled or not.
  42850. */
  42851. get: function () {
  42852. return this._imageProcessingConfiguration.toneMappingEnabled;
  42853. },
  42854. /**
  42855. * Sets wether tonemapping is enabled or not
  42856. */
  42857. set: function (value) {
  42858. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42859. },
  42860. enumerable: true,
  42861. configurable: true
  42862. });
  42863. ;
  42864. ;
  42865. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42866. /**
  42867. * The camera exposure used on this material.
  42868. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42869. * This corresponds to a photographic exposure.
  42870. */
  42871. get: function () {
  42872. return this._imageProcessingConfiguration.exposure;
  42873. },
  42874. /**
  42875. * The camera exposure used on this material.
  42876. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42877. * This corresponds to a photographic exposure.
  42878. */
  42879. set: function (value) {
  42880. this._imageProcessingConfiguration.exposure = value;
  42881. },
  42882. enumerable: true,
  42883. configurable: true
  42884. });
  42885. ;
  42886. ;
  42887. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42888. /**
  42889. * Gets The camera contrast used on this material.
  42890. */
  42891. get: function () {
  42892. return this._imageProcessingConfiguration.contrast;
  42893. },
  42894. /**
  42895. * Sets The camera contrast used on this material.
  42896. */
  42897. set: function (value) {
  42898. this._imageProcessingConfiguration.contrast = value;
  42899. },
  42900. enumerable: true,
  42901. configurable: true
  42902. });
  42903. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42904. /**
  42905. * Gets the Color Grading 2D Lookup Texture.
  42906. */
  42907. get: function () {
  42908. return this._imageProcessingConfiguration.colorGradingTexture;
  42909. },
  42910. /**
  42911. * Sets the Color Grading 2D Lookup Texture.
  42912. */
  42913. set: function (value) {
  42914. this._imageProcessingConfiguration.colorGradingTexture = value;
  42915. },
  42916. enumerable: true,
  42917. configurable: true
  42918. });
  42919. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42920. /**
  42921. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42922. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42923. * 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;
  42924. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42925. */
  42926. get: function () {
  42927. return this._imageProcessingConfiguration.colorCurves;
  42928. },
  42929. /**
  42930. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42931. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42932. * 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;
  42933. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42934. */
  42935. set: function (value) {
  42936. this._imageProcessingConfiguration.colorCurves = value;
  42937. },
  42938. enumerable: true,
  42939. configurable: true
  42940. });
  42941. StandardMaterial.prototype.getClassName = function () {
  42942. return "StandardMaterial";
  42943. };
  42944. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42945. get: function () {
  42946. return this._useLogarithmicDepth;
  42947. },
  42948. set: function (value) {
  42949. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42950. this._markAllSubMeshesAsMiscDirty();
  42951. },
  42952. enumerable: true,
  42953. configurable: true
  42954. });
  42955. StandardMaterial.prototype.needAlphaBlending = function () {
  42956. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42957. };
  42958. StandardMaterial.prototype.needAlphaTesting = function () {
  42959. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42960. };
  42961. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42962. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42963. };
  42964. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42965. return this._diffuseTexture;
  42966. };
  42967. /**
  42968. * Child classes can use it to update shaders
  42969. */
  42970. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42971. if (useInstances === void 0) { useInstances = false; }
  42972. if (subMesh.effect && this.isFrozen) {
  42973. if (this._wasPreviouslyReady && subMesh.effect) {
  42974. return true;
  42975. }
  42976. }
  42977. if (!subMesh._materialDefines) {
  42978. subMesh._materialDefines = new StandardMaterialDefines();
  42979. }
  42980. var scene = this.getScene();
  42981. var defines = subMesh._materialDefines;
  42982. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42983. if (defines._renderId === scene.getRenderId()) {
  42984. return true;
  42985. }
  42986. }
  42987. var engine = scene.getEngine();
  42988. // Lights
  42989. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42990. // Textures
  42991. if (defines._areTexturesDirty) {
  42992. defines._needUVs = false;
  42993. defines.MAINUV1 = false;
  42994. defines.MAINUV2 = false;
  42995. if (scene.texturesEnabled) {
  42996. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42997. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42998. return false;
  42999. }
  43000. else {
  43001. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43002. }
  43003. }
  43004. else {
  43005. defines.DIFFUSE = false;
  43006. }
  43007. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43008. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43009. return false;
  43010. }
  43011. else {
  43012. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43013. }
  43014. }
  43015. else {
  43016. defines.AMBIENT = false;
  43017. }
  43018. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43019. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43020. return false;
  43021. }
  43022. else {
  43023. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43024. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43025. }
  43026. }
  43027. else {
  43028. defines.OPACITY = false;
  43029. }
  43030. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43031. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43032. return false;
  43033. }
  43034. else {
  43035. defines._needNormals = true;
  43036. defines.REFLECTION = true;
  43037. defines.ROUGHNESS = (this._roughness > 0);
  43038. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43039. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43040. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43041. switch (this._reflectionTexture.coordinatesMode) {
  43042. case BABYLON.Texture.EXPLICIT_MODE:
  43043. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43044. break;
  43045. case BABYLON.Texture.PLANAR_MODE:
  43046. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43047. break;
  43048. case BABYLON.Texture.PROJECTION_MODE:
  43049. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43050. break;
  43051. case BABYLON.Texture.SKYBOX_MODE:
  43052. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43053. break;
  43054. case BABYLON.Texture.SPHERICAL_MODE:
  43055. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43056. break;
  43057. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43058. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43059. break;
  43060. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43061. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43062. break;
  43063. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43064. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43065. break;
  43066. case BABYLON.Texture.CUBIC_MODE:
  43067. case BABYLON.Texture.INVCUBIC_MODE:
  43068. default:
  43069. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43070. break;
  43071. }
  43072. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43073. }
  43074. }
  43075. else {
  43076. defines.REFLECTION = false;
  43077. }
  43078. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43079. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43080. return false;
  43081. }
  43082. else {
  43083. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43084. }
  43085. }
  43086. else {
  43087. defines.EMISSIVE = false;
  43088. }
  43089. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43090. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43091. return false;
  43092. }
  43093. else {
  43094. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43095. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43096. }
  43097. }
  43098. else {
  43099. defines.LIGHTMAP = false;
  43100. }
  43101. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43102. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43103. return false;
  43104. }
  43105. else {
  43106. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43107. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43108. }
  43109. }
  43110. else {
  43111. defines.SPECULAR = false;
  43112. }
  43113. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43114. // Bump texure can not be not blocking.
  43115. if (!this._bumpTexture.isReady()) {
  43116. return false;
  43117. }
  43118. else {
  43119. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43120. defines.PARALLAX = this._useParallax;
  43121. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43122. }
  43123. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43124. }
  43125. else {
  43126. defines.BUMP = false;
  43127. }
  43128. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43129. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43130. return false;
  43131. }
  43132. else {
  43133. defines._needUVs = true;
  43134. defines.REFRACTION = true;
  43135. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43136. }
  43137. }
  43138. else {
  43139. defines.REFRACTION = false;
  43140. }
  43141. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43142. }
  43143. else {
  43144. defines.DIFFUSE = false;
  43145. defines.AMBIENT = false;
  43146. defines.OPACITY = false;
  43147. defines.REFLECTION = false;
  43148. defines.EMISSIVE = false;
  43149. defines.LIGHTMAP = false;
  43150. defines.BUMP = false;
  43151. defines.REFRACTION = false;
  43152. }
  43153. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43154. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43155. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43156. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43157. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43158. }
  43159. if (defines._areImageProcessingDirty) {
  43160. if (!this._imageProcessingConfiguration.isReady()) {
  43161. return false;
  43162. }
  43163. this._imageProcessingConfiguration.prepareDefines(defines);
  43164. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43165. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43166. }
  43167. if (defines._areFresnelDirty) {
  43168. if (StandardMaterial.FresnelEnabled) {
  43169. // Fresnel
  43170. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43171. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43172. this._reflectionFresnelParameters) {
  43173. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43174. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43175. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43176. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43177. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43178. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43179. defines._needNormals = true;
  43180. defines.FRESNEL = true;
  43181. }
  43182. }
  43183. else {
  43184. defines.FRESNEL = false;
  43185. }
  43186. }
  43187. // Misc.
  43188. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43189. // Attribs
  43190. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43191. // Values that need to be evaluated on every frame
  43192. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43193. // Get correct effect
  43194. if (defines.isDirty) {
  43195. defines.markAsProcessed();
  43196. scene.resetCachedMaterial();
  43197. // Fallbacks
  43198. var fallbacks = new BABYLON.EffectFallbacks();
  43199. if (defines.REFLECTION) {
  43200. fallbacks.addFallback(0, "REFLECTION");
  43201. }
  43202. if (defines.SPECULAR) {
  43203. fallbacks.addFallback(0, "SPECULAR");
  43204. }
  43205. if (defines.BUMP) {
  43206. fallbacks.addFallback(0, "BUMP");
  43207. }
  43208. if (defines.PARALLAX) {
  43209. fallbacks.addFallback(1, "PARALLAX");
  43210. }
  43211. if (defines.PARALLAXOCCLUSION) {
  43212. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43213. }
  43214. if (defines.SPECULAROVERALPHA) {
  43215. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43216. }
  43217. if (defines.FOG) {
  43218. fallbacks.addFallback(1, "FOG");
  43219. }
  43220. if (defines.POINTSIZE) {
  43221. fallbacks.addFallback(0, "POINTSIZE");
  43222. }
  43223. if (defines.LOGARITHMICDEPTH) {
  43224. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43225. }
  43226. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43227. if (defines.SPECULARTERM) {
  43228. fallbacks.addFallback(0, "SPECULARTERM");
  43229. }
  43230. if (defines.DIFFUSEFRESNEL) {
  43231. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43232. }
  43233. if (defines.OPACITYFRESNEL) {
  43234. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43235. }
  43236. if (defines.REFLECTIONFRESNEL) {
  43237. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43238. }
  43239. if (defines.EMISSIVEFRESNEL) {
  43240. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43241. }
  43242. if (defines.FRESNEL) {
  43243. fallbacks.addFallback(4, "FRESNEL");
  43244. }
  43245. //Attributes
  43246. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43247. if (defines.NORMAL) {
  43248. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43249. }
  43250. if (defines.UV1) {
  43251. attribs.push(BABYLON.VertexBuffer.UVKind);
  43252. }
  43253. if (defines.UV2) {
  43254. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43255. }
  43256. if (defines.VERTEXCOLOR) {
  43257. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43258. }
  43259. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43260. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43261. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43262. var shaderName = "default";
  43263. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43264. "vFogInfos", "vFogColor", "pointSize",
  43265. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43266. "mBones",
  43267. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43268. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43269. "vReflectionPosition", "vReflectionSize",
  43270. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43271. ];
  43272. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43273. var uniformBuffers = ["Material", "Scene"];
  43274. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43275. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43276. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43277. uniformsNames: uniforms,
  43278. uniformBuffersNames: uniformBuffers,
  43279. samplers: samplers,
  43280. defines: defines,
  43281. maxSimultaneousLights: this._maxSimultaneousLights
  43282. });
  43283. if (this.customShaderNameResolve) {
  43284. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43285. }
  43286. var join = defines.toString();
  43287. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43288. attributes: attribs,
  43289. uniformsNames: uniforms,
  43290. uniformBuffersNames: uniformBuffers,
  43291. samplers: samplers,
  43292. defines: join,
  43293. fallbacks: fallbacks,
  43294. onCompiled: this.onCompiled,
  43295. onError: this.onError,
  43296. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43297. }, engine), defines);
  43298. this.buildUniformLayout();
  43299. }
  43300. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43301. return false;
  43302. }
  43303. defines._renderId = scene.getRenderId();
  43304. this._wasPreviouslyReady = true;
  43305. return true;
  43306. };
  43307. StandardMaterial.prototype.buildUniformLayout = function () {
  43308. // Order is important !
  43309. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43310. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43311. this._uniformBuffer.addUniform("opacityParts", 4);
  43312. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43313. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43314. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43315. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43316. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43317. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43318. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43319. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43320. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43321. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43322. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43323. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43324. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43325. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43326. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43327. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43328. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43329. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43330. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43331. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43332. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43333. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43334. this._uniformBuffer.addUniform("specularMatrix", 16);
  43335. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43336. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43337. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43338. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43339. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43340. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43341. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43342. this._uniformBuffer.addUniform("pointSize", 1);
  43343. this._uniformBuffer.create();
  43344. };
  43345. StandardMaterial.prototype.unbind = function () {
  43346. if (this._activeEffect) {
  43347. var needFlag = false;
  43348. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43349. this._activeEffect.setTexture("reflection2DSampler", null);
  43350. needFlag = true;
  43351. }
  43352. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43353. this._activeEffect.setTexture("refraction2DSampler", null);
  43354. needFlag = true;
  43355. }
  43356. if (needFlag) {
  43357. this._markAllSubMeshesAsTexturesDirty();
  43358. }
  43359. }
  43360. _super.prototype.unbind.call(this);
  43361. };
  43362. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43363. var scene = this.getScene();
  43364. var defines = subMesh._materialDefines;
  43365. if (!defines) {
  43366. return;
  43367. }
  43368. var effect = subMesh.effect;
  43369. if (!effect) {
  43370. return;
  43371. }
  43372. this._activeEffect = effect;
  43373. // Matrices
  43374. this.bindOnlyWorldMatrix(world);
  43375. // Normal Matrix
  43376. if (defines.OBJECTSPACE_NORMALMAP) {
  43377. world.toNormalMatrix(this._normalMatrix);
  43378. this.bindOnlyNormalMatrix(this._normalMatrix);
  43379. }
  43380. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43381. // Bones
  43382. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43383. if (mustRebind) {
  43384. this._uniformBuffer.bindToEffect(effect, "Material");
  43385. this.bindViewProjection(effect);
  43386. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43387. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43388. // Fresnel
  43389. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43390. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43391. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43392. }
  43393. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43394. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43395. }
  43396. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43397. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43398. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43399. }
  43400. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43401. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43402. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43403. }
  43404. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43405. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43406. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43407. }
  43408. }
  43409. // Textures
  43410. if (scene.texturesEnabled) {
  43411. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43412. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43413. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43414. if (this._diffuseTexture.hasAlpha) {
  43415. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43416. }
  43417. }
  43418. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43419. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43420. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43421. }
  43422. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43423. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43424. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43425. }
  43426. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43427. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43428. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43429. if (this._reflectionTexture.boundingBoxSize) {
  43430. var cubeTexture = this._reflectionTexture;
  43431. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43432. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43433. }
  43434. }
  43435. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43436. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43437. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43438. }
  43439. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43440. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43441. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43442. }
  43443. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43444. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43445. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43446. }
  43447. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43448. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43449. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43450. if (scene._mirroredCameraPosition) {
  43451. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43452. }
  43453. else {
  43454. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43455. }
  43456. }
  43457. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43458. var depth = 1.0;
  43459. if (!this._refractionTexture.isCube) {
  43460. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43461. if (this._refractionTexture.depth) {
  43462. depth = this._refractionTexture.depth;
  43463. }
  43464. }
  43465. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43466. }
  43467. }
  43468. // Point size
  43469. if (this.pointsCloud) {
  43470. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43471. }
  43472. if (defines.SPECULARTERM) {
  43473. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43474. }
  43475. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43476. // Diffuse
  43477. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43478. }
  43479. // Textures
  43480. if (scene.texturesEnabled) {
  43481. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43482. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43483. }
  43484. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43485. effect.setTexture("ambientSampler", this._ambientTexture);
  43486. }
  43487. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43488. effect.setTexture("opacitySampler", this._opacityTexture);
  43489. }
  43490. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43491. if (this._reflectionTexture.isCube) {
  43492. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43493. }
  43494. else {
  43495. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43496. }
  43497. }
  43498. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43499. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43500. }
  43501. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43502. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43503. }
  43504. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43505. effect.setTexture("specularSampler", this._specularTexture);
  43506. }
  43507. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43508. effect.setTexture("bumpSampler", this._bumpTexture);
  43509. }
  43510. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43511. var depth = 1.0;
  43512. if (this._refractionTexture.isCube) {
  43513. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43514. }
  43515. else {
  43516. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43517. }
  43518. }
  43519. }
  43520. // Clip plane
  43521. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43522. // Colors
  43523. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43524. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43525. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43526. }
  43527. if (mustRebind || !this.isFrozen) {
  43528. // Lights
  43529. if (scene.lightsEnabled && !this._disableLighting) {
  43530. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43531. }
  43532. // View
  43533. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43534. this.bindView(effect);
  43535. }
  43536. // Fog
  43537. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43538. // Morph targets
  43539. if (defines.NUM_MORPH_INFLUENCERS) {
  43540. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43541. }
  43542. // Log. depth
  43543. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43544. // image processing
  43545. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43546. this._imageProcessingConfiguration.bind(this._activeEffect);
  43547. }
  43548. }
  43549. this._uniformBuffer.update();
  43550. this._afterBind(mesh, this._activeEffect);
  43551. };
  43552. StandardMaterial.prototype.getAnimatables = function () {
  43553. var results = [];
  43554. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43555. results.push(this._diffuseTexture);
  43556. }
  43557. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43558. results.push(this._ambientTexture);
  43559. }
  43560. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43561. results.push(this._opacityTexture);
  43562. }
  43563. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43564. results.push(this._reflectionTexture);
  43565. }
  43566. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43567. results.push(this._emissiveTexture);
  43568. }
  43569. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43570. results.push(this._specularTexture);
  43571. }
  43572. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43573. results.push(this._bumpTexture);
  43574. }
  43575. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43576. results.push(this._lightmapTexture);
  43577. }
  43578. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43579. results.push(this._refractionTexture);
  43580. }
  43581. return results;
  43582. };
  43583. StandardMaterial.prototype.getActiveTextures = function () {
  43584. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43585. if (this._diffuseTexture) {
  43586. activeTextures.push(this._diffuseTexture);
  43587. }
  43588. if (this._ambientTexture) {
  43589. activeTextures.push(this._ambientTexture);
  43590. }
  43591. if (this._opacityTexture) {
  43592. activeTextures.push(this._opacityTexture);
  43593. }
  43594. if (this._reflectionTexture) {
  43595. activeTextures.push(this._reflectionTexture);
  43596. }
  43597. if (this._emissiveTexture) {
  43598. activeTextures.push(this._emissiveTexture);
  43599. }
  43600. if (this._specularTexture) {
  43601. activeTextures.push(this._specularTexture);
  43602. }
  43603. if (this._bumpTexture) {
  43604. activeTextures.push(this._bumpTexture);
  43605. }
  43606. if (this._lightmapTexture) {
  43607. activeTextures.push(this._lightmapTexture);
  43608. }
  43609. if (this._refractionTexture) {
  43610. activeTextures.push(this._refractionTexture);
  43611. }
  43612. return activeTextures;
  43613. };
  43614. StandardMaterial.prototype.hasTexture = function (texture) {
  43615. if (_super.prototype.hasTexture.call(this, texture)) {
  43616. return true;
  43617. }
  43618. if (this._diffuseTexture === texture) {
  43619. return true;
  43620. }
  43621. if (this._ambientTexture === texture) {
  43622. return true;
  43623. }
  43624. if (this._opacityTexture === texture) {
  43625. return true;
  43626. }
  43627. if (this._reflectionTexture === texture) {
  43628. return true;
  43629. }
  43630. if (this._emissiveTexture === texture) {
  43631. return true;
  43632. }
  43633. if (this._specularTexture === texture) {
  43634. return true;
  43635. }
  43636. if (this._bumpTexture === texture) {
  43637. return true;
  43638. }
  43639. if (this._lightmapTexture === texture) {
  43640. return true;
  43641. }
  43642. if (this._refractionTexture === texture) {
  43643. return true;
  43644. }
  43645. return false;
  43646. };
  43647. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43648. if (forceDisposeTextures) {
  43649. if (this._diffuseTexture) {
  43650. this._diffuseTexture.dispose();
  43651. }
  43652. if (this._ambientTexture) {
  43653. this._ambientTexture.dispose();
  43654. }
  43655. if (this._opacityTexture) {
  43656. this._opacityTexture.dispose();
  43657. }
  43658. if (this._reflectionTexture) {
  43659. this._reflectionTexture.dispose();
  43660. }
  43661. if (this._emissiveTexture) {
  43662. this._emissiveTexture.dispose();
  43663. }
  43664. if (this._specularTexture) {
  43665. this._specularTexture.dispose();
  43666. }
  43667. if (this._bumpTexture) {
  43668. this._bumpTexture.dispose();
  43669. }
  43670. if (this._lightmapTexture) {
  43671. this._lightmapTexture.dispose();
  43672. }
  43673. if (this._refractionTexture) {
  43674. this._refractionTexture.dispose();
  43675. }
  43676. }
  43677. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43678. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43679. }
  43680. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43681. };
  43682. StandardMaterial.prototype.clone = function (name) {
  43683. var _this = this;
  43684. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43685. result.name = name;
  43686. result.id = name;
  43687. return result;
  43688. };
  43689. StandardMaterial.prototype.serialize = function () {
  43690. return BABYLON.SerializationHelper.Serialize(this);
  43691. };
  43692. // Statics
  43693. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43694. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43695. };
  43696. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43697. get: function () {
  43698. return StandardMaterial._DiffuseTextureEnabled;
  43699. },
  43700. set: function (value) {
  43701. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43702. return;
  43703. }
  43704. StandardMaterial._DiffuseTextureEnabled = value;
  43705. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43706. },
  43707. enumerable: true,
  43708. configurable: true
  43709. });
  43710. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43711. get: function () {
  43712. return StandardMaterial._AmbientTextureEnabled;
  43713. },
  43714. set: function (value) {
  43715. if (StandardMaterial._AmbientTextureEnabled === value) {
  43716. return;
  43717. }
  43718. StandardMaterial._AmbientTextureEnabled = value;
  43719. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43720. },
  43721. enumerable: true,
  43722. configurable: true
  43723. });
  43724. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43725. get: function () {
  43726. return StandardMaterial._OpacityTextureEnabled;
  43727. },
  43728. set: function (value) {
  43729. if (StandardMaterial._OpacityTextureEnabled === value) {
  43730. return;
  43731. }
  43732. StandardMaterial._OpacityTextureEnabled = value;
  43733. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43734. },
  43735. enumerable: true,
  43736. configurable: true
  43737. });
  43738. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43739. get: function () {
  43740. return StandardMaterial._ReflectionTextureEnabled;
  43741. },
  43742. set: function (value) {
  43743. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43744. return;
  43745. }
  43746. StandardMaterial._ReflectionTextureEnabled = value;
  43747. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43748. },
  43749. enumerable: true,
  43750. configurable: true
  43751. });
  43752. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43753. get: function () {
  43754. return StandardMaterial._EmissiveTextureEnabled;
  43755. },
  43756. set: function (value) {
  43757. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43758. return;
  43759. }
  43760. StandardMaterial._EmissiveTextureEnabled = value;
  43761. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43762. },
  43763. enumerable: true,
  43764. configurable: true
  43765. });
  43766. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43767. get: function () {
  43768. return StandardMaterial._SpecularTextureEnabled;
  43769. },
  43770. set: function (value) {
  43771. if (StandardMaterial._SpecularTextureEnabled === value) {
  43772. return;
  43773. }
  43774. StandardMaterial._SpecularTextureEnabled = value;
  43775. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43776. },
  43777. enumerable: true,
  43778. configurable: true
  43779. });
  43780. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43781. get: function () {
  43782. return StandardMaterial._BumpTextureEnabled;
  43783. },
  43784. set: function (value) {
  43785. if (StandardMaterial._BumpTextureEnabled === value) {
  43786. return;
  43787. }
  43788. StandardMaterial._BumpTextureEnabled = value;
  43789. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43790. },
  43791. enumerable: true,
  43792. configurable: true
  43793. });
  43794. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43795. get: function () {
  43796. return StandardMaterial._LightmapTextureEnabled;
  43797. },
  43798. set: function (value) {
  43799. if (StandardMaterial._LightmapTextureEnabled === value) {
  43800. return;
  43801. }
  43802. StandardMaterial._LightmapTextureEnabled = value;
  43803. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43804. },
  43805. enumerable: true,
  43806. configurable: true
  43807. });
  43808. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43809. get: function () {
  43810. return StandardMaterial._RefractionTextureEnabled;
  43811. },
  43812. set: function (value) {
  43813. if (StandardMaterial._RefractionTextureEnabled === value) {
  43814. return;
  43815. }
  43816. StandardMaterial._RefractionTextureEnabled = value;
  43817. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43818. },
  43819. enumerable: true,
  43820. configurable: true
  43821. });
  43822. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43823. get: function () {
  43824. return StandardMaterial._ColorGradingTextureEnabled;
  43825. },
  43826. set: function (value) {
  43827. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43828. return;
  43829. }
  43830. StandardMaterial._ColorGradingTextureEnabled = value;
  43831. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43832. },
  43833. enumerable: true,
  43834. configurable: true
  43835. });
  43836. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43837. get: function () {
  43838. return StandardMaterial._FresnelEnabled;
  43839. },
  43840. set: function (value) {
  43841. if (StandardMaterial._FresnelEnabled === value) {
  43842. return;
  43843. }
  43844. StandardMaterial._FresnelEnabled = value;
  43845. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43846. },
  43847. enumerable: true,
  43848. configurable: true
  43849. });
  43850. // Flags used to enable or disable a type of texture for all Standard Materials
  43851. StandardMaterial._DiffuseTextureEnabled = true;
  43852. StandardMaterial._AmbientTextureEnabled = true;
  43853. StandardMaterial._OpacityTextureEnabled = true;
  43854. StandardMaterial._ReflectionTextureEnabled = true;
  43855. StandardMaterial._EmissiveTextureEnabled = true;
  43856. StandardMaterial._SpecularTextureEnabled = true;
  43857. StandardMaterial._BumpTextureEnabled = true;
  43858. StandardMaterial._LightmapTextureEnabled = true;
  43859. StandardMaterial._RefractionTextureEnabled = true;
  43860. StandardMaterial._ColorGradingTextureEnabled = true;
  43861. StandardMaterial._FresnelEnabled = true;
  43862. __decorate([
  43863. BABYLON.serializeAsTexture("diffuseTexture")
  43864. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43865. __decorate([
  43866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43867. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43868. __decorate([
  43869. BABYLON.serializeAsTexture("ambientTexture")
  43870. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43871. __decorate([
  43872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43873. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43874. __decorate([
  43875. BABYLON.serializeAsTexture("opacityTexture")
  43876. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43877. __decorate([
  43878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43879. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43880. __decorate([
  43881. BABYLON.serializeAsTexture("reflectionTexture")
  43882. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43883. __decorate([
  43884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43885. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43886. __decorate([
  43887. BABYLON.serializeAsTexture("emissiveTexture")
  43888. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43889. __decorate([
  43890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43891. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43892. __decorate([
  43893. BABYLON.serializeAsTexture("specularTexture")
  43894. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43895. __decorate([
  43896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43897. ], StandardMaterial.prototype, "specularTexture", void 0);
  43898. __decorate([
  43899. BABYLON.serializeAsTexture("bumpTexture")
  43900. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43901. __decorate([
  43902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43903. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43904. __decorate([
  43905. BABYLON.serializeAsTexture("lightmapTexture")
  43906. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43907. __decorate([
  43908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43909. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43910. __decorate([
  43911. BABYLON.serializeAsTexture("refractionTexture")
  43912. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43913. __decorate([
  43914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43915. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43916. __decorate([
  43917. BABYLON.serializeAsColor3("ambient")
  43918. ], StandardMaterial.prototype, "ambientColor", void 0);
  43919. __decorate([
  43920. BABYLON.serializeAsColor3("diffuse")
  43921. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43922. __decorate([
  43923. BABYLON.serializeAsColor3("specular")
  43924. ], StandardMaterial.prototype, "specularColor", void 0);
  43925. __decorate([
  43926. BABYLON.serializeAsColor3("emissive")
  43927. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43928. __decorate([
  43929. BABYLON.serialize()
  43930. ], StandardMaterial.prototype, "specularPower", void 0);
  43931. __decorate([
  43932. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43933. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43934. __decorate([
  43935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43936. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43937. __decorate([
  43938. BABYLON.serialize("useEmissiveAsIllumination")
  43939. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43940. __decorate([
  43941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43942. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43943. __decorate([
  43944. BABYLON.serialize("linkEmissiveWithDiffuse")
  43945. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43946. __decorate([
  43947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43948. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43949. __decorate([
  43950. BABYLON.serialize("useSpecularOverAlpha")
  43951. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43952. __decorate([
  43953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43954. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43955. __decorate([
  43956. BABYLON.serialize("useReflectionOverAlpha")
  43957. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43958. __decorate([
  43959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43960. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43961. __decorate([
  43962. BABYLON.serialize("disableLighting")
  43963. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43964. __decorate([
  43965. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43966. ], StandardMaterial.prototype, "disableLighting", void 0);
  43967. __decorate([
  43968. BABYLON.serialize("useObjectSpaceNormalMap")
  43969. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43970. __decorate([
  43971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43972. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43973. __decorate([
  43974. BABYLON.serialize("useParallax")
  43975. ], StandardMaterial.prototype, "_useParallax", void 0);
  43976. __decorate([
  43977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43978. ], StandardMaterial.prototype, "useParallax", void 0);
  43979. __decorate([
  43980. BABYLON.serialize("useParallaxOcclusion")
  43981. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43982. __decorate([
  43983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43984. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43985. __decorate([
  43986. BABYLON.serialize()
  43987. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43988. __decorate([
  43989. BABYLON.serialize("roughness")
  43990. ], StandardMaterial.prototype, "_roughness", void 0);
  43991. __decorate([
  43992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43993. ], StandardMaterial.prototype, "roughness", void 0);
  43994. __decorate([
  43995. BABYLON.serialize()
  43996. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43997. __decorate([
  43998. BABYLON.serialize()
  43999. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44000. __decorate([
  44001. BABYLON.serialize()
  44002. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44003. __decorate([
  44004. BABYLON.serialize("useLightmapAsShadowmap")
  44005. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44006. __decorate([
  44007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44008. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44009. __decorate([
  44010. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44011. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44012. __decorate([
  44013. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44014. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44015. __decorate([
  44016. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44017. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44018. __decorate([
  44019. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44020. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44021. __decorate([
  44022. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44023. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44024. __decorate([
  44025. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44026. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44027. __decorate([
  44028. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44029. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44030. __decorate([
  44031. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44032. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44033. __decorate([
  44034. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44035. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44036. __decorate([
  44037. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44038. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44039. __decorate([
  44040. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44041. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44042. __decorate([
  44043. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44044. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44045. __decorate([
  44046. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44047. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44048. __decorate([
  44049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44050. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44051. __decorate([
  44052. BABYLON.serialize("maxSimultaneousLights")
  44053. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44054. __decorate([
  44055. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44056. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44057. __decorate([
  44058. BABYLON.serialize("invertNormalMapX")
  44059. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44060. __decorate([
  44061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44062. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44063. __decorate([
  44064. BABYLON.serialize("invertNormalMapY")
  44065. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44066. __decorate([
  44067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44068. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44069. __decorate([
  44070. BABYLON.serialize("twoSidedLighting")
  44071. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44072. __decorate([
  44073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44074. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44075. __decorate([
  44076. BABYLON.serialize()
  44077. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44078. return StandardMaterial;
  44079. }(BABYLON.PushMaterial));
  44080. BABYLON.StandardMaterial = StandardMaterial;
  44081. })(BABYLON || (BABYLON = {}));
  44082. //# sourceMappingURL=babylon.standardMaterial.js.map
  44083. var BABYLON;
  44084. (function (BABYLON) {
  44085. /**
  44086. * Manages the defines for the PBR Material.
  44087. * @hiddenChildren
  44088. */
  44089. var PBRMaterialDefines = /** @class */ (function (_super) {
  44090. __extends(PBRMaterialDefines, _super);
  44091. /**
  44092. * Initializes the PBR Material defines.
  44093. */
  44094. function PBRMaterialDefines() {
  44095. var _this = _super.call(this) || this;
  44096. _this.PBR = true;
  44097. _this.MAINUV1 = false;
  44098. _this.MAINUV2 = false;
  44099. _this.UV1 = false;
  44100. _this.UV2 = false;
  44101. _this.ALBEDO = false;
  44102. _this.ALBEDODIRECTUV = 0;
  44103. _this.VERTEXCOLOR = false;
  44104. _this.AMBIENT = false;
  44105. _this.AMBIENTDIRECTUV = 0;
  44106. _this.AMBIENTINGRAYSCALE = false;
  44107. _this.OPACITY = false;
  44108. _this.VERTEXALPHA = false;
  44109. _this.OPACITYDIRECTUV = 0;
  44110. _this.OPACITYRGB = false;
  44111. _this.ALPHATEST = false;
  44112. _this.DEPTHPREPASS = false;
  44113. _this.ALPHABLEND = false;
  44114. _this.ALPHAFROMALBEDO = false;
  44115. _this.ALPHATESTVALUE = "0.5";
  44116. _this.SPECULAROVERALPHA = false;
  44117. _this.RADIANCEOVERALPHA = false;
  44118. _this.ALPHAFRESNEL = false;
  44119. _this.LINEARALPHAFRESNEL = false;
  44120. _this.PREMULTIPLYALPHA = false;
  44121. _this.EMISSIVE = false;
  44122. _this.EMISSIVEDIRECTUV = 0;
  44123. _this.REFLECTIVITY = false;
  44124. _this.REFLECTIVITYDIRECTUV = 0;
  44125. _this.SPECULARTERM = false;
  44126. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44127. _this.MICROSURFACEAUTOMATIC = false;
  44128. _this.LODBASEDMICROSFURACE = false;
  44129. _this.MICROSURFACEMAP = false;
  44130. _this.MICROSURFACEMAPDIRECTUV = 0;
  44131. _this.METALLICWORKFLOW = false;
  44132. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44133. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44134. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44135. _this.AOSTOREINMETALMAPRED = false;
  44136. _this.ENVIRONMENTBRDF = false;
  44137. _this.NORMAL = false;
  44138. _this.TANGENT = false;
  44139. _this.BUMP = false;
  44140. _this.BUMPDIRECTUV = 0;
  44141. _this.OBJECTSPACE_NORMALMAP = false;
  44142. _this.PARALLAX = false;
  44143. _this.PARALLAXOCCLUSION = false;
  44144. _this.NORMALXYSCALE = true;
  44145. _this.LIGHTMAP = false;
  44146. _this.LIGHTMAPDIRECTUV = 0;
  44147. _this.USELIGHTMAPASSHADOWMAP = false;
  44148. _this.GAMMALIGHTMAP = false;
  44149. _this.REFLECTION = false;
  44150. _this.REFLECTIONMAP_3D = false;
  44151. _this.REFLECTIONMAP_SPHERICAL = false;
  44152. _this.REFLECTIONMAP_PLANAR = false;
  44153. _this.REFLECTIONMAP_CUBIC = false;
  44154. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44155. _this.REFLECTIONMAP_PROJECTION = false;
  44156. _this.REFLECTIONMAP_SKYBOX = false;
  44157. _this.REFLECTIONMAP_EXPLICIT = false;
  44158. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44159. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44160. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44161. _this.INVERTCUBICMAP = false;
  44162. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44163. _this.USESPHERICALINVERTEX = false;
  44164. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44165. _this.LODINREFLECTIONALPHA = false;
  44166. _this.GAMMAREFLECTION = false;
  44167. _this.RADIANCEOCCLUSION = false;
  44168. _this.HORIZONOCCLUSION = false;
  44169. _this.REFRACTION = false;
  44170. _this.REFRACTIONMAP_3D = false;
  44171. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44172. _this.LODINREFRACTIONALPHA = false;
  44173. _this.GAMMAREFRACTION = false;
  44174. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44175. _this.INSTANCES = false;
  44176. _this.NUM_BONE_INFLUENCERS = 0;
  44177. _this.BonesPerMesh = 0;
  44178. _this.NONUNIFORMSCALING = false;
  44179. _this.MORPHTARGETS = false;
  44180. _this.MORPHTARGETS_NORMAL = false;
  44181. _this.MORPHTARGETS_TANGENT = false;
  44182. _this.NUM_MORPH_INFLUENCERS = 0;
  44183. _this.IMAGEPROCESSING = false;
  44184. _this.VIGNETTE = false;
  44185. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44186. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44187. _this.TONEMAPPING = false;
  44188. _this.CONTRAST = false;
  44189. _this.COLORCURVES = false;
  44190. _this.COLORGRADING = false;
  44191. _this.COLORGRADING3D = false;
  44192. _this.SAMPLER3DGREENDEPTH = false;
  44193. _this.SAMPLER3DBGRMAP = false;
  44194. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44195. _this.EXPOSURE = false;
  44196. _this.USEPHYSICALLIGHTFALLOFF = false;
  44197. _this.TWOSIDEDLIGHTING = false;
  44198. _this.SHADOWFLOAT = false;
  44199. _this.CLIPPLANE = false;
  44200. _this.POINTSIZE = false;
  44201. _this.FOG = false;
  44202. _this.LOGARITHMICDEPTH = false;
  44203. _this.FORCENORMALFORWARD = false;
  44204. _this.SPECULARAA = false;
  44205. _this.UNLIT = false;
  44206. _this.rebuild();
  44207. return _this;
  44208. }
  44209. /**
  44210. * Resets the PBR Material defines.
  44211. */
  44212. PBRMaterialDefines.prototype.reset = function () {
  44213. _super.prototype.reset.call(this);
  44214. this.ALPHATESTVALUE = "0.5";
  44215. this.PBR = true;
  44216. };
  44217. return PBRMaterialDefines;
  44218. }(BABYLON.MaterialDefines));
  44219. /**
  44220. * The Physically based material base class of BJS.
  44221. *
  44222. * This offers the main features of a standard PBR material.
  44223. * For more information, please refer to the documentation :
  44224. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44225. */
  44226. var PBRBaseMaterial = /** @class */ (function (_super) {
  44227. __extends(PBRBaseMaterial, _super);
  44228. /**
  44229. * Instantiates a new PBRMaterial instance.
  44230. *
  44231. * @param name The material name
  44232. * @param scene The scene the material will be use in.
  44233. */
  44234. function PBRBaseMaterial(name, scene) {
  44235. var _this = _super.call(this, name, scene) || this;
  44236. /**
  44237. * Intensity of the direct lights e.g. the four lights available in your scene.
  44238. * This impacts both the direct diffuse and specular highlights.
  44239. */
  44240. _this._directIntensity = 1.0;
  44241. /**
  44242. * Intensity of the emissive part of the material.
  44243. * This helps controlling the emissive effect without modifying the emissive color.
  44244. */
  44245. _this._emissiveIntensity = 1.0;
  44246. /**
  44247. * Intensity of the environment e.g. how much the environment will light the object
  44248. * either through harmonics for rough material or through the refelction for shiny ones.
  44249. */
  44250. _this._environmentIntensity = 1.0;
  44251. /**
  44252. * This is a special control allowing the reduction of the specular highlights coming from the
  44253. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44254. */
  44255. _this._specularIntensity = 1.0;
  44256. /**
  44257. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44258. */
  44259. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44260. /**
  44261. * Debug Control allowing disabling the bump map on this material.
  44262. */
  44263. _this._disableBumpMap = false;
  44264. /**
  44265. * AKA Occlusion Texture Intensity in other nomenclature.
  44266. */
  44267. _this._ambientTextureStrength = 1.0;
  44268. /**
  44269. * The color of a material in ambient lighting.
  44270. */
  44271. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44272. /**
  44273. * AKA Diffuse Color in other nomenclature.
  44274. */
  44275. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44276. /**
  44277. * AKA Specular Color in other nomenclature.
  44278. */
  44279. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44280. /**
  44281. * The color applied when light is reflected from a material.
  44282. */
  44283. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44284. /**
  44285. * The color applied when light is emitted from a material.
  44286. */
  44287. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44288. /**
  44289. * AKA Glossiness in other nomenclature.
  44290. */
  44291. _this._microSurface = 0.9;
  44292. /**
  44293. * source material index of refraction (IOR)' / 'destination material IOR.
  44294. */
  44295. _this._indexOfRefraction = 0.66;
  44296. /**
  44297. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44298. */
  44299. _this._invertRefractionY = false;
  44300. /**
  44301. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44302. * Materials half opaque for instance using refraction could benefit from this control.
  44303. */
  44304. _this._linkRefractionWithTransparency = false;
  44305. /**
  44306. * Specifies that the material will use the light map as a show map.
  44307. */
  44308. _this._useLightmapAsShadowmap = false;
  44309. /**
  44310. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44311. * makes the reflect vector face the model (under horizon).
  44312. */
  44313. _this._useHorizonOcclusion = true;
  44314. /**
  44315. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44316. * too much the area relying on ambient texture to define their ambient occlusion.
  44317. */
  44318. _this._useRadianceOcclusion = true;
  44319. /**
  44320. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44321. */
  44322. _this._useAlphaFromAlbedoTexture = false;
  44323. /**
  44324. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44325. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44326. */
  44327. _this._useSpecularOverAlpha = true;
  44328. /**
  44329. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44330. */
  44331. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44332. /**
  44333. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44334. */
  44335. _this._useRoughnessFromMetallicTextureAlpha = true;
  44336. /**
  44337. * Specifies if the metallic texture contains the roughness information in its green channel.
  44338. */
  44339. _this._useRoughnessFromMetallicTextureGreen = false;
  44340. /**
  44341. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44342. */
  44343. _this._useMetallnessFromMetallicTextureBlue = false;
  44344. /**
  44345. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44346. */
  44347. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44348. /**
  44349. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44350. */
  44351. _this._useAmbientInGrayScale = false;
  44352. /**
  44353. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44354. * The material will try to infer what glossiness each pixel should be.
  44355. */
  44356. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44357. /**
  44358. * BJS is using an harcoded light falloff based on a manually sets up range.
  44359. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44360. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44361. */
  44362. _this._usePhysicalLightFalloff = true;
  44363. /**
  44364. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44365. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44366. */
  44367. _this._useRadianceOverAlpha = true;
  44368. /**
  44369. * Allows using an object space normal map (instead of tangent space).
  44370. */
  44371. _this._useObjectSpaceNormalMap = false;
  44372. /**
  44373. * Allows using the bump map in parallax mode.
  44374. */
  44375. _this._useParallax = false;
  44376. /**
  44377. * Allows using the bump map in parallax occlusion mode.
  44378. */
  44379. _this._useParallaxOcclusion = false;
  44380. /**
  44381. * Controls the scale bias of the parallax mode.
  44382. */
  44383. _this._parallaxScaleBias = 0.05;
  44384. /**
  44385. * If sets to true, disables all the lights affecting the material.
  44386. */
  44387. _this._disableLighting = false;
  44388. /**
  44389. * Number of Simultaneous lights allowed on the material.
  44390. */
  44391. _this._maxSimultaneousLights = 4;
  44392. /**
  44393. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44394. */
  44395. _this._invertNormalMapX = false;
  44396. /**
  44397. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44398. */
  44399. _this._invertNormalMapY = false;
  44400. /**
  44401. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44402. */
  44403. _this._twoSidedLighting = false;
  44404. /**
  44405. * Defines the alpha limits in alpha test mode.
  44406. */
  44407. _this._alphaCutOff = 0.4;
  44408. /**
  44409. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44410. */
  44411. _this._forceAlphaTest = false;
  44412. /**
  44413. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44414. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44415. */
  44416. _this._useAlphaFresnel = false;
  44417. /**
  44418. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44419. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44420. */
  44421. _this._useLinearAlphaFresnel = false;
  44422. /**
  44423. * The transparency mode of the material.
  44424. */
  44425. _this._transparencyMode = null;
  44426. /**
  44427. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44428. * from cos thetav and roughness:
  44429. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44430. */
  44431. _this._environmentBRDFTexture = null;
  44432. /**
  44433. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44434. */
  44435. _this._forceIrradianceInFragment = false;
  44436. /**
  44437. * Force normal to face away from face.
  44438. */
  44439. _this._forceNormalForward = false;
  44440. /**
  44441. * Enables specular anti aliasing in the PBR shader.
  44442. * It will both interacts on the Geometry for analytical and IBL lighting.
  44443. * It also prefilter the roughness map based on the bump values.
  44444. */
  44445. _this._enableSpecularAntiAliasing = false;
  44446. /**
  44447. * Stores the available render targets.
  44448. */
  44449. _this._renderTargets = new BABYLON.SmartArray(16);
  44450. /**
  44451. * Sets the global ambient color for the material used in lighting calculations.
  44452. */
  44453. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44454. /**
  44455. * If set to true, no lighting calculations will be applied.
  44456. */
  44457. _this._unlit = false;
  44458. // Setup the default processing configuration to the scene.
  44459. _this._attachImageProcessingConfiguration(null);
  44460. _this.getRenderTargetTextures = function () {
  44461. _this._renderTargets.reset();
  44462. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44463. _this._renderTargets.push(_this._reflectionTexture);
  44464. }
  44465. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44466. _this._renderTargets.push(_this._refractionTexture);
  44467. }
  44468. return _this._renderTargets;
  44469. };
  44470. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44471. return _this;
  44472. }
  44473. /**
  44474. * Attaches a new image processing configuration to the PBR Material.
  44475. * @param configuration
  44476. */
  44477. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44478. var _this = this;
  44479. if (configuration === this._imageProcessingConfiguration) {
  44480. return;
  44481. }
  44482. // Detaches observer.
  44483. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44484. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44485. }
  44486. // Pick the scene configuration if needed.
  44487. if (!configuration) {
  44488. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44489. }
  44490. else {
  44491. this._imageProcessingConfiguration = configuration;
  44492. }
  44493. // Attaches observer.
  44494. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44495. _this._markAllSubMeshesAsImageProcessingDirty();
  44496. });
  44497. };
  44498. /**
  44499. * Gets the name of the material class.
  44500. */
  44501. PBRBaseMaterial.prototype.getClassName = function () {
  44502. return "PBRBaseMaterial";
  44503. };
  44504. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44505. /**
  44506. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44507. */
  44508. get: function () {
  44509. return this._useLogarithmicDepth;
  44510. },
  44511. /**
  44512. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44513. */
  44514. set: function (value) {
  44515. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44516. },
  44517. enumerable: true,
  44518. configurable: true
  44519. });
  44520. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44521. /**
  44522. * Gets the current transparency mode.
  44523. */
  44524. get: function () {
  44525. return this._transparencyMode;
  44526. },
  44527. /**
  44528. * Sets the transparency mode of the material.
  44529. */
  44530. set: function (value) {
  44531. if (this._transparencyMode === value) {
  44532. return;
  44533. }
  44534. this._transparencyMode = value;
  44535. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44536. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44537. },
  44538. enumerable: true,
  44539. configurable: true
  44540. });
  44541. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44542. /**
  44543. * Returns true if alpha blending should be disabled.
  44544. */
  44545. get: function () {
  44546. return (this._linkRefractionWithTransparency ||
  44547. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44548. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44549. },
  44550. enumerable: true,
  44551. configurable: true
  44552. });
  44553. /**
  44554. * Specifies whether or not this material should be rendered in alpha blend mode.
  44555. */
  44556. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44557. if (this._disableAlphaBlending) {
  44558. return false;
  44559. }
  44560. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44561. };
  44562. /**
  44563. * Specifies if the mesh will require alpha blending.
  44564. * @param mesh - BJS mesh.
  44565. */
  44566. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44567. if (this._disableAlphaBlending) {
  44568. return false;
  44569. }
  44570. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44571. };
  44572. /**
  44573. * Specifies whether or not this material should be rendered in alpha test mode.
  44574. */
  44575. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44576. if (this._forceAlphaTest) {
  44577. return true;
  44578. }
  44579. if (this._linkRefractionWithTransparency) {
  44580. return false;
  44581. }
  44582. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44583. };
  44584. /**
  44585. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44586. */
  44587. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44588. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44589. };
  44590. /**
  44591. * Gets the texture used for the alpha test.
  44592. */
  44593. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44594. return this._albedoTexture;
  44595. };
  44596. /**
  44597. * Specifies that the submesh is ready to be used.
  44598. * @param mesh - BJS mesh.
  44599. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44600. * @param useInstances - Specifies that instances should be used.
  44601. * @returns - boolean indicating that the submesh is ready or not.
  44602. */
  44603. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44604. if (subMesh.effect && this.isFrozen) {
  44605. if (this._wasPreviouslyReady) {
  44606. return true;
  44607. }
  44608. }
  44609. if (!subMesh._materialDefines) {
  44610. subMesh._materialDefines = new PBRMaterialDefines();
  44611. }
  44612. var defines = subMesh._materialDefines;
  44613. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44614. if (defines._renderId === this.getScene().getRenderId()) {
  44615. return true;
  44616. }
  44617. }
  44618. var scene = this.getScene();
  44619. var engine = scene.getEngine();
  44620. if (defines._areTexturesDirty) {
  44621. if (scene.texturesEnabled) {
  44622. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44623. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44624. return false;
  44625. }
  44626. }
  44627. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44628. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44629. return false;
  44630. }
  44631. }
  44632. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44633. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44634. return false;
  44635. }
  44636. }
  44637. var reflectionTexture = this._getReflectionTexture();
  44638. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44639. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44640. return false;
  44641. }
  44642. }
  44643. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44644. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44645. return false;
  44646. }
  44647. }
  44648. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44649. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44650. return false;
  44651. }
  44652. }
  44653. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44654. if (this._metallicTexture) {
  44655. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44656. return false;
  44657. }
  44658. }
  44659. else if (this._reflectivityTexture) {
  44660. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44661. return false;
  44662. }
  44663. }
  44664. if (this._microSurfaceTexture) {
  44665. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44666. return false;
  44667. }
  44668. }
  44669. }
  44670. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44671. // Bump texture cannot be not blocking.
  44672. if (!this._bumpTexture.isReady()) {
  44673. return false;
  44674. }
  44675. }
  44676. var refractionTexture = this._getRefractionTexture();
  44677. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44678. if (!refractionTexture.isReadyOrNotBlocking()) {
  44679. return false;
  44680. }
  44681. }
  44682. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44683. // This is blocking.
  44684. if (!this._environmentBRDFTexture.isReady()) {
  44685. return false;
  44686. }
  44687. }
  44688. }
  44689. }
  44690. if (defines._areImageProcessingDirty) {
  44691. if (!this._imageProcessingConfiguration.isReady()) {
  44692. return false;
  44693. }
  44694. }
  44695. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44696. mesh.createNormals(true);
  44697. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44698. }
  44699. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44700. if (effect) {
  44701. scene.resetCachedMaterial();
  44702. subMesh.setEffect(effect, defines);
  44703. this.buildUniformLayout();
  44704. }
  44705. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44706. return false;
  44707. }
  44708. defines._renderId = scene.getRenderId();
  44709. this._wasPreviouslyReady = true;
  44710. return true;
  44711. };
  44712. /**
  44713. * Specifies if the material uses metallic roughness workflow.
  44714. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44715. */
  44716. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44717. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44718. return true;
  44719. }
  44720. return false;
  44721. };
  44722. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44723. if (onCompiled === void 0) { onCompiled = null; }
  44724. if (onError === void 0) { onError = null; }
  44725. if (useInstances === void 0) { useInstances = null; }
  44726. if (useClipPlane === void 0) { useClipPlane = null; }
  44727. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44728. if (!defines.isDirty) {
  44729. return null;
  44730. }
  44731. defines.markAsProcessed();
  44732. var scene = this.getScene();
  44733. var engine = scene.getEngine();
  44734. // Fallbacks
  44735. var fallbacks = new BABYLON.EffectFallbacks();
  44736. var fallbackRank = 0;
  44737. if (defines.USESPHERICALINVERTEX) {
  44738. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44739. }
  44740. if (defines.FOG) {
  44741. fallbacks.addFallback(fallbackRank, "FOG");
  44742. }
  44743. if (defines.POINTSIZE) {
  44744. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44745. }
  44746. if (defines.LOGARITHMICDEPTH) {
  44747. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44748. }
  44749. if (defines.PARALLAX) {
  44750. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44751. }
  44752. if (defines.PARALLAXOCCLUSION) {
  44753. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44754. }
  44755. if (defines.ENVIRONMENTBRDF) {
  44756. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44757. }
  44758. if (defines.TANGENT) {
  44759. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44760. }
  44761. if (defines.BUMP) {
  44762. fallbacks.addFallback(fallbackRank++, "BUMP");
  44763. }
  44764. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44765. if (defines.SPECULARTERM) {
  44766. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44767. }
  44768. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44769. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44770. }
  44771. if (defines.LIGHTMAP) {
  44772. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44773. }
  44774. if (defines.NORMAL) {
  44775. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44776. }
  44777. if (defines.AMBIENT) {
  44778. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44779. }
  44780. if (defines.EMISSIVE) {
  44781. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44782. }
  44783. if (defines.VERTEXCOLOR) {
  44784. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44785. }
  44786. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44787. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44788. }
  44789. if (defines.MORPHTARGETS) {
  44790. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44791. }
  44792. //Attributes
  44793. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44794. if (defines.NORMAL) {
  44795. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44796. }
  44797. if (defines.TANGENT) {
  44798. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44799. }
  44800. if (defines.UV1) {
  44801. attribs.push(BABYLON.VertexBuffer.UVKind);
  44802. }
  44803. if (defines.UV2) {
  44804. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44805. }
  44806. if (defines.VERTEXCOLOR) {
  44807. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44808. }
  44809. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44810. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44811. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44812. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44813. "vFogInfos", "vFogColor", "pointSize",
  44814. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44815. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44816. "mBones",
  44817. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44818. "vLightingIntensity",
  44819. "logarithmicDepthConstant",
  44820. "vSphericalX", "vSphericalY", "vSphericalZ",
  44821. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44822. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44823. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44824. "vTangentSpaceParams"
  44825. ];
  44826. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44827. "bumpSampler", "lightmapSampler", "opacitySampler",
  44828. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44829. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44830. "microSurfaceSampler", "environmentBrdfSampler"];
  44831. var uniformBuffers = ["Material", "Scene"];
  44832. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44833. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44834. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44835. uniformsNames: uniforms,
  44836. uniformBuffersNames: uniformBuffers,
  44837. samplers: samplers,
  44838. defines: defines,
  44839. maxSimultaneousLights: this._maxSimultaneousLights
  44840. });
  44841. var join = defines.toString();
  44842. return engine.createEffect("pbr", {
  44843. attributes: attribs,
  44844. uniformsNames: uniforms,
  44845. uniformBuffersNames: uniformBuffers,
  44846. samplers: samplers,
  44847. defines: join,
  44848. fallbacks: fallbacks,
  44849. onCompiled: onCompiled,
  44850. onError: onError,
  44851. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44852. }, engine);
  44853. };
  44854. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44855. if (useInstances === void 0) { useInstances = null; }
  44856. if (useClipPlane === void 0) { useClipPlane = null; }
  44857. var scene = this.getScene();
  44858. var engine = scene.getEngine();
  44859. // Lights
  44860. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44861. defines._needNormals = true;
  44862. // Textures
  44863. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44864. if (defines._areTexturesDirty) {
  44865. defines._needUVs = false;
  44866. if (scene.texturesEnabled) {
  44867. if (scene.getEngine().getCaps().textureLOD) {
  44868. defines.LODBASEDMICROSFURACE = true;
  44869. }
  44870. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44871. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44872. }
  44873. else {
  44874. defines.ALBEDO = false;
  44875. }
  44876. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44877. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44878. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44879. }
  44880. else {
  44881. defines.AMBIENT = false;
  44882. }
  44883. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44884. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44885. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44886. }
  44887. else {
  44888. defines.OPACITY = false;
  44889. }
  44890. var reflectionTexture = this._getReflectionTexture();
  44891. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44892. defines.REFLECTION = true;
  44893. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44894. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44895. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44896. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44897. defines.INVERTCUBICMAP = true;
  44898. }
  44899. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44900. switch (reflectionTexture.coordinatesMode) {
  44901. case BABYLON.Texture.EXPLICIT_MODE:
  44902. defines.REFLECTIONMAP_EXPLICIT = true;
  44903. break;
  44904. case BABYLON.Texture.PLANAR_MODE:
  44905. defines.REFLECTIONMAP_PLANAR = true;
  44906. break;
  44907. case BABYLON.Texture.PROJECTION_MODE:
  44908. defines.REFLECTIONMAP_PROJECTION = true;
  44909. break;
  44910. case BABYLON.Texture.SKYBOX_MODE:
  44911. defines.REFLECTIONMAP_SKYBOX = true;
  44912. break;
  44913. case BABYLON.Texture.SPHERICAL_MODE:
  44914. defines.REFLECTIONMAP_SPHERICAL = true;
  44915. break;
  44916. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44917. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44918. break;
  44919. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44920. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44921. break;
  44922. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44923. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44924. break;
  44925. case BABYLON.Texture.CUBIC_MODE:
  44926. case BABYLON.Texture.INVCUBIC_MODE:
  44927. default:
  44928. defines.REFLECTIONMAP_CUBIC = true;
  44929. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44930. break;
  44931. }
  44932. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44933. if (reflectionTexture.sphericalPolynomial) {
  44934. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44935. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44936. defines.USESPHERICALINVERTEX = false;
  44937. }
  44938. else {
  44939. defines.USESPHERICALINVERTEX = true;
  44940. }
  44941. }
  44942. }
  44943. }
  44944. else {
  44945. defines.REFLECTION = false;
  44946. defines.REFLECTIONMAP_3D = false;
  44947. defines.REFLECTIONMAP_SPHERICAL = false;
  44948. defines.REFLECTIONMAP_PLANAR = false;
  44949. defines.REFLECTIONMAP_CUBIC = false;
  44950. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44951. defines.REFLECTIONMAP_PROJECTION = false;
  44952. defines.REFLECTIONMAP_SKYBOX = false;
  44953. defines.REFLECTIONMAP_EXPLICIT = false;
  44954. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44955. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44956. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44957. defines.INVERTCUBICMAP = false;
  44958. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44959. defines.USESPHERICALINVERTEX = false;
  44960. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44961. defines.LODINREFLECTIONALPHA = false;
  44962. defines.GAMMAREFLECTION = false;
  44963. }
  44964. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44965. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44966. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44967. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44968. }
  44969. else {
  44970. defines.LIGHTMAP = false;
  44971. }
  44972. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44973. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44974. }
  44975. else {
  44976. defines.EMISSIVE = false;
  44977. }
  44978. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44979. if (this._metallicTexture) {
  44980. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44981. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44982. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44983. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44984. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44985. }
  44986. else if (this._reflectivityTexture) {
  44987. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44988. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44989. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44990. }
  44991. else {
  44992. defines.REFLECTIVITY = false;
  44993. }
  44994. if (this._microSurfaceTexture) {
  44995. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44996. }
  44997. else {
  44998. defines.MICROSURFACEMAP = false;
  44999. }
  45000. }
  45001. else {
  45002. defines.REFLECTIVITY = false;
  45003. defines.MICROSURFACEMAP = false;
  45004. }
  45005. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45006. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45007. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45008. defines.PARALLAX = true;
  45009. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45010. }
  45011. else {
  45012. defines.PARALLAX = false;
  45013. }
  45014. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45015. }
  45016. else {
  45017. defines.BUMP = false;
  45018. }
  45019. var refractionTexture = this._getRefractionTexture();
  45020. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45021. defines.REFRACTION = true;
  45022. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45023. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45024. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45025. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45026. if (this._linkRefractionWithTransparency) {
  45027. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45028. }
  45029. }
  45030. else {
  45031. defines.REFRACTION = false;
  45032. }
  45033. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45034. defines.ENVIRONMENTBRDF = true;
  45035. }
  45036. else {
  45037. defines.ENVIRONMENTBRDF = false;
  45038. }
  45039. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45040. defines.ALPHAFROMALBEDO = true;
  45041. }
  45042. else {
  45043. defines.ALPHAFROMALBEDO = false;
  45044. }
  45045. }
  45046. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45047. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45048. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45049. if (!this.backFaceCulling && this._twoSidedLighting) {
  45050. defines.TWOSIDEDLIGHTING = true;
  45051. }
  45052. else {
  45053. defines.TWOSIDEDLIGHTING = false;
  45054. }
  45055. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45056. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45057. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45058. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45059. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45060. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45061. }
  45062. if (defines._areImageProcessingDirty) {
  45063. this._imageProcessingConfiguration.prepareDefines(defines);
  45064. }
  45065. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45066. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45067. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45068. // Misc.
  45069. if (defines._areMiscDirty) {
  45070. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45071. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45072. }
  45073. // Values that need to be evaluated on every frame
  45074. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45075. // Attribs
  45076. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45077. };
  45078. /**
  45079. * Force shader compilation
  45080. */
  45081. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45082. var _this = this;
  45083. var localOptions = __assign({ clipPlane: false }, options);
  45084. var defines = new PBRMaterialDefines();
  45085. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45086. if (effect.isReady()) {
  45087. if (onCompiled) {
  45088. onCompiled(this);
  45089. }
  45090. }
  45091. else {
  45092. effect.onCompileObservable.add(function () {
  45093. if (onCompiled) {
  45094. onCompiled(_this);
  45095. }
  45096. });
  45097. }
  45098. };
  45099. /**
  45100. * Initializes the uniform buffer layout for the shader.
  45101. */
  45102. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45103. // Order is important !
  45104. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45105. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45106. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45107. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45108. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45109. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45110. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45111. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45112. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45113. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45114. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45115. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45116. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45117. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45118. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45119. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45120. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45121. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45122. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45123. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45124. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45125. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45126. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45127. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45128. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45129. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45130. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45131. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45132. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45133. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45134. this._uniformBuffer.addUniform("pointSize", 1);
  45135. this._uniformBuffer.create();
  45136. };
  45137. /**
  45138. * Unbinds the textures.
  45139. */
  45140. PBRBaseMaterial.prototype.unbind = function () {
  45141. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45142. this._uniformBuffer.setTexture("reflectionSampler", null);
  45143. }
  45144. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45145. this._uniformBuffer.setTexture("refractionSampler", null);
  45146. }
  45147. _super.prototype.unbind.call(this);
  45148. };
  45149. /**
  45150. * Binds the submesh data.
  45151. * @param world - The world matrix.
  45152. * @param mesh - The BJS mesh.
  45153. * @param subMesh - A submesh of the BJS mesh.
  45154. */
  45155. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45156. var scene = this.getScene();
  45157. var defines = subMesh._materialDefines;
  45158. if (!defines) {
  45159. return;
  45160. }
  45161. var effect = subMesh.effect;
  45162. if (!effect) {
  45163. return;
  45164. }
  45165. this._activeEffect = effect;
  45166. // Matrices
  45167. this.bindOnlyWorldMatrix(world);
  45168. // Normal Matrix
  45169. if (defines.OBJECTSPACE_NORMALMAP) {
  45170. world.toNormalMatrix(this._normalMatrix);
  45171. this.bindOnlyNormalMatrix(this._normalMatrix);
  45172. }
  45173. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45174. // Bones
  45175. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45176. var reflectionTexture = null;
  45177. if (mustRebind) {
  45178. this._uniformBuffer.bindToEffect(effect, "Material");
  45179. this.bindViewProjection(effect);
  45180. reflectionTexture = this._getReflectionTexture();
  45181. var refractionTexture = this._getRefractionTexture();
  45182. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45183. // Texture uniforms
  45184. if (scene.texturesEnabled) {
  45185. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45186. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45187. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45188. }
  45189. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45190. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45191. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45192. }
  45193. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45194. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45195. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45196. }
  45197. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45198. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45199. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45200. if (reflectionTexture.boundingBoxSize) {
  45201. var cubeTexture = reflectionTexture;
  45202. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45203. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45204. }
  45205. var polynomials = reflectionTexture.sphericalPolynomial;
  45206. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45207. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45208. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45209. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45210. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45211. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45212. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45213. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45214. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45215. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45216. }
  45217. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45218. }
  45219. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45220. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45221. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45222. }
  45223. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45224. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45225. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45226. }
  45227. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45228. if (this._metallicTexture) {
  45229. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45230. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45231. }
  45232. else if (this._reflectivityTexture) {
  45233. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45234. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45235. }
  45236. if (this._microSurfaceTexture) {
  45237. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45238. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45239. }
  45240. }
  45241. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45242. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45243. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45244. if (scene._mirroredCameraPosition) {
  45245. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45246. }
  45247. else {
  45248. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45249. }
  45250. }
  45251. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45252. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45253. var depth = 1.0;
  45254. if (!refractionTexture.isCube) {
  45255. if (refractionTexture.depth) {
  45256. depth = refractionTexture.depth;
  45257. }
  45258. }
  45259. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45260. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45261. }
  45262. }
  45263. // Point size
  45264. if (this.pointsCloud) {
  45265. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45266. }
  45267. // Colors
  45268. if (defines.METALLICWORKFLOW) {
  45269. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45270. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45271. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45272. }
  45273. else {
  45274. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45275. }
  45276. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45277. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45278. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45279. // Misc
  45280. this._lightingInfos.x = this._directIntensity;
  45281. this._lightingInfos.y = this._emissiveIntensity;
  45282. this._lightingInfos.z = this._environmentIntensity;
  45283. this._lightingInfos.w = this._specularIntensity;
  45284. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45285. }
  45286. // Textures
  45287. if (scene.texturesEnabled) {
  45288. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45289. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45290. }
  45291. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45292. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45293. }
  45294. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45295. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45296. }
  45297. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45298. if (defines.LODBASEDMICROSFURACE) {
  45299. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45300. }
  45301. else {
  45302. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45303. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45304. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45305. }
  45306. }
  45307. if (defines.ENVIRONMENTBRDF) {
  45308. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45309. }
  45310. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45311. if (defines.LODBASEDMICROSFURACE) {
  45312. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45313. }
  45314. else {
  45315. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45316. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45317. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45318. }
  45319. }
  45320. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45321. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45322. }
  45323. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45324. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45325. }
  45326. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45327. if (this._metallicTexture) {
  45328. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45329. }
  45330. else if (this._reflectivityTexture) {
  45331. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45332. }
  45333. if (this._microSurfaceTexture) {
  45334. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45335. }
  45336. }
  45337. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45338. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45339. }
  45340. }
  45341. // Clip plane
  45342. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45343. // Colors
  45344. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45345. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45346. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45347. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45348. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45349. }
  45350. if (mustRebind || !this.isFrozen) {
  45351. // Lights
  45352. if (scene.lightsEnabled && !this._disableLighting) {
  45353. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45354. }
  45355. // View
  45356. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45357. this.bindView(effect);
  45358. }
  45359. // Fog
  45360. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45361. // Morph targets
  45362. if (defines.NUM_MORPH_INFLUENCERS) {
  45363. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45364. }
  45365. // image processing
  45366. this._imageProcessingConfiguration.bind(this._activeEffect);
  45367. // Log. depth
  45368. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45369. }
  45370. this._uniformBuffer.update();
  45371. this._afterBind(mesh, this._activeEffect);
  45372. };
  45373. /**
  45374. * Returns the animatable textures.
  45375. * @returns - Array of animatable textures.
  45376. */
  45377. PBRBaseMaterial.prototype.getAnimatables = function () {
  45378. var results = [];
  45379. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45380. results.push(this._albedoTexture);
  45381. }
  45382. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45383. results.push(this._ambientTexture);
  45384. }
  45385. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45386. results.push(this._opacityTexture);
  45387. }
  45388. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45389. results.push(this._reflectionTexture);
  45390. }
  45391. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45392. results.push(this._emissiveTexture);
  45393. }
  45394. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45395. results.push(this._metallicTexture);
  45396. }
  45397. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45398. results.push(this._reflectivityTexture);
  45399. }
  45400. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45401. results.push(this._bumpTexture);
  45402. }
  45403. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45404. results.push(this._lightmapTexture);
  45405. }
  45406. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45407. results.push(this._refractionTexture);
  45408. }
  45409. return results;
  45410. };
  45411. /**
  45412. * Returns the texture used for reflections.
  45413. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45414. */
  45415. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45416. if (this._reflectionTexture) {
  45417. return this._reflectionTexture;
  45418. }
  45419. return this.getScene().environmentTexture;
  45420. };
  45421. /**
  45422. * Returns the texture used for refraction or null if none is used.
  45423. * @returns - Refection texture if present. If no refraction texture and refraction
  45424. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45425. */
  45426. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45427. if (this._refractionTexture) {
  45428. return this._refractionTexture;
  45429. }
  45430. if (this._linkRefractionWithTransparency) {
  45431. return this.getScene().environmentTexture;
  45432. }
  45433. return null;
  45434. };
  45435. /**
  45436. * Disposes the resources of the material.
  45437. * @param forceDisposeEffect - Forces the disposal of effects.
  45438. * @param forceDisposeTextures - Forces the disposal of all textures.
  45439. */
  45440. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45441. if (forceDisposeTextures) {
  45442. if (this._albedoTexture) {
  45443. this._albedoTexture.dispose();
  45444. }
  45445. if (this._ambientTexture) {
  45446. this._ambientTexture.dispose();
  45447. }
  45448. if (this._opacityTexture) {
  45449. this._opacityTexture.dispose();
  45450. }
  45451. if (this._reflectionTexture) {
  45452. this._reflectionTexture.dispose();
  45453. }
  45454. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45455. this._environmentBRDFTexture.dispose();
  45456. }
  45457. if (this._emissiveTexture) {
  45458. this._emissiveTexture.dispose();
  45459. }
  45460. if (this._metallicTexture) {
  45461. this._metallicTexture.dispose();
  45462. }
  45463. if (this._reflectivityTexture) {
  45464. this._reflectivityTexture.dispose();
  45465. }
  45466. if (this._bumpTexture) {
  45467. this._bumpTexture.dispose();
  45468. }
  45469. if (this._lightmapTexture) {
  45470. this._lightmapTexture.dispose();
  45471. }
  45472. if (this._refractionTexture) {
  45473. this._refractionTexture.dispose();
  45474. }
  45475. }
  45476. this._renderTargets.dispose();
  45477. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45478. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45479. }
  45480. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45481. };
  45482. /**
  45483. * Stores the reflectivity values based on metallic roughness workflow.
  45484. */
  45485. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45486. __decorate([
  45487. BABYLON.serializeAsImageProcessingConfiguration()
  45488. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45489. __decorate([
  45490. BABYLON.serialize()
  45491. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45492. __decorate([
  45493. BABYLON.serialize()
  45494. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45495. return PBRBaseMaterial;
  45496. }(BABYLON.PushMaterial));
  45497. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45498. })(BABYLON || (BABYLON = {}));
  45499. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45500. var BABYLON;
  45501. (function (BABYLON) {
  45502. /**
  45503. * The Physically based simple base material of BJS.
  45504. *
  45505. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45506. * It is used as the base class for both the specGloss and metalRough conventions.
  45507. */
  45508. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45509. __extends(PBRBaseSimpleMaterial, _super);
  45510. /**
  45511. * Instantiates a new PBRMaterial instance.
  45512. *
  45513. * @param name The material name
  45514. * @param scene The scene the material will be use in.
  45515. */
  45516. function PBRBaseSimpleMaterial(name, scene) {
  45517. var _this = _super.call(this, name, scene) || this;
  45518. /**
  45519. * Number of Simultaneous lights allowed on the material.
  45520. */
  45521. _this.maxSimultaneousLights = 4;
  45522. /**
  45523. * If sets to true, disables all the lights affecting the material.
  45524. */
  45525. _this.disableLighting = false;
  45526. /**
  45527. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45528. */
  45529. _this.invertNormalMapX = false;
  45530. /**
  45531. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45532. */
  45533. _this.invertNormalMapY = false;
  45534. /**
  45535. * Emissivie color used to self-illuminate the model.
  45536. */
  45537. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45538. /**
  45539. * Occlusion Channel Strenght.
  45540. */
  45541. _this.occlusionStrength = 1.0;
  45542. _this.useLightmapAsShadowmap = false;
  45543. _this._useAlphaFromAlbedoTexture = true;
  45544. _this._useAmbientInGrayScale = true;
  45545. return _this;
  45546. }
  45547. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45548. /**
  45549. * Gets the current double sided mode.
  45550. */
  45551. get: function () {
  45552. return this._twoSidedLighting;
  45553. },
  45554. /**
  45555. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45556. */
  45557. set: function (value) {
  45558. if (this._twoSidedLighting === value) {
  45559. return;
  45560. }
  45561. this._twoSidedLighting = value;
  45562. this.backFaceCulling = !value;
  45563. this._markAllSubMeshesAsTexturesDirty();
  45564. },
  45565. enumerable: true,
  45566. configurable: true
  45567. });
  45568. /**
  45569. * Return the active textures of the material.
  45570. */
  45571. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45572. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45573. if (this.environmentTexture) {
  45574. activeTextures.push(this.environmentTexture);
  45575. }
  45576. if (this.normalTexture) {
  45577. activeTextures.push(this.normalTexture);
  45578. }
  45579. if (this.emissiveTexture) {
  45580. activeTextures.push(this.emissiveTexture);
  45581. }
  45582. if (this.occlusionTexture) {
  45583. activeTextures.push(this.occlusionTexture);
  45584. }
  45585. if (this.lightmapTexture) {
  45586. activeTextures.push(this.lightmapTexture);
  45587. }
  45588. return activeTextures;
  45589. };
  45590. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45591. if (_super.prototype.hasTexture.call(this, texture)) {
  45592. return true;
  45593. }
  45594. if (this.lightmapTexture === texture) {
  45595. return true;
  45596. }
  45597. return false;
  45598. };
  45599. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45600. return "PBRBaseSimpleMaterial";
  45601. };
  45602. __decorate([
  45603. BABYLON.serialize(),
  45604. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45605. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45606. __decorate([
  45607. BABYLON.serialize(),
  45608. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45609. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45610. __decorate([
  45611. BABYLON.serializeAsTexture(),
  45612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45613. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45614. __decorate([
  45615. BABYLON.serialize(),
  45616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45617. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45618. __decorate([
  45619. BABYLON.serialize(),
  45620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45621. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45622. __decorate([
  45623. BABYLON.serializeAsTexture(),
  45624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45625. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45626. __decorate([
  45627. BABYLON.serializeAsColor3("emissive"),
  45628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45629. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45630. __decorate([
  45631. BABYLON.serializeAsTexture(),
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45633. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45634. __decorate([
  45635. BABYLON.serialize(),
  45636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45637. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45638. __decorate([
  45639. BABYLON.serializeAsTexture(),
  45640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45641. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45642. __decorate([
  45643. BABYLON.serialize(),
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45645. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45646. __decorate([
  45647. BABYLON.serialize()
  45648. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45649. __decorate([
  45650. BABYLON.serializeAsTexture(),
  45651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45652. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45653. __decorate([
  45654. BABYLON.serialize(),
  45655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45656. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45657. return PBRBaseSimpleMaterial;
  45658. }(BABYLON.PBRBaseMaterial));
  45659. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45660. })(BABYLON || (BABYLON = {}));
  45661. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45662. var BABYLON;
  45663. (function (BABYLON) {
  45664. /**
  45665. * The Physically based material of BJS.
  45666. *
  45667. * This offers the main features of a standard PBR material.
  45668. * For more information, please refer to the documentation :
  45669. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45670. */
  45671. var PBRMaterial = /** @class */ (function (_super) {
  45672. __extends(PBRMaterial, _super);
  45673. /**
  45674. * Instantiates a new PBRMaterial instance.
  45675. *
  45676. * @param name The material name
  45677. * @param scene The scene the material will be use in.
  45678. */
  45679. function PBRMaterial(name, scene) {
  45680. var _this = _super.call(this, name, scene) || this;
  45681. /**
  45682. * Intensity of the direct lights e.g. the four lights available in your scene.
  45683. * This impacts both the direct diffuse and specular highlights.
  45684. */
  45685. _this.directIntensity = 1.0;
  45686. /**
  45687. * Intensity of the emissive part of the material.
  45688. * This helps controlling the emissive effect without modifying the emissive color.
  45689. */
  45690. _this.emissiveIntensity = 1.0;
  45691. /**
  45692. * Intensity of the environment e.g. how much the environment will light the object
  45693. * either through harmonics for rough material or through the refelction for shiny ones.
  45694. */
  45695. _this.environmentIntensity = 1.0;
  45696. /**
  45697. * This is a special control allowing the reduction of the specular highlights coming from the
  45698. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45699. */
  45700. _this.specularIntensity = 1.0;
  45701. /**
  45702. * Debug Control allowing disabling the bump map on this material.
  45703. */
  45704. _this.disableBumpMap = false;
  45705. /**
  45706. * AKA Occlusion Texture Intensity in other nomenclature.
  45707. */
  45708. _this.ambientTextureStrength = 1.0;
  45709. /**
  45710. * The color of a material in ambient lighting.
  45711. */
  45712. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45713. /**
  45714. * AKA Diffuse Color in other nomenclature.
  45715. */
  45716. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45717. /**
  45718. * AKA Specular Color in other nomenclature.
  45719. */
  45720. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45721. /**
  45722. * The color reflected from the material.
  45723. */
  45724. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45725. /**
  45726. * The color emitted from the material.
  45727. */
  45728. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45729. /**
  45730. * AKA Glossiness in other nomenclature.
  45731. */
  45732. _this.microSurface = 1.0;
  45733. /**
  45734. * source material index of refraction (IOR)' / 'destination material IOR.
  45735. */
  45736. _this.indexOfRefraction = 0.66;
  45737. /**
  45738. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45739. */
  45740. _this.invertRefractionY = false;
  45741. /**
  45742. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45743. * Materials half opaque for instance using refraction could benefit from this control.
  45744. */
  45745. _this.linkRefractionWithTransparency = false;
  45746. _this.useLightmapAsShadowmap = false;
  45747. /**
  45748. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45749. */
  45750. _this.useAlphaFromAlbedoTexture = false;
  45751. /**
  45752. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45753. */
  45754. _this.forceAlphaTest = false;
  45755. /**
  45756. * Defines the alpha limits in alpha test mode.
  45757. */
  45758. _this.alphaCutOff = 0.4;
  45759. /**
  45760. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45761. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45762. */
  45763. _this.useSpecularOverAlpha = true;
  45764. /**
  45765. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45766. */
  45767. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45768. /**
  45769. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45770. */
  45771. _this.useRoughnessFromMetallicTextureAlpha = true;
  45772. /**
  45773. * Specifies if the metallic texture contains the roughness information in its green channel.
  45774. */
  45775. _this.useRoughnessFromMetallicTextureGreen = false;
  45776. /**
  45777. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45778. */
  45779. _this.useMetallnessFromMetallicTextureBlue = false;
  45780. /**
  45781. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45782. */
  45783. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45784. /**
  45785. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45786. */
  45787. _this.useAmbientInGrayScale = false;
  45788. /**
  45789. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45790. * The material will try to infer what glossiness each pixel should be.
  45791. */
  45792. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45793. /**
  45794. * BJS is using an harcoded light falloff based on a manually sets up range.
  45795. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45796. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45797. */
  45798. _this.usePhysicalLightFalloff = true;
  45799. /**
  45800. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45801. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45802. */
  45803. _this.useRadianceOverAlpha = true;
  45804. /**
  45805. * Allows using an object space normal map (instead of tangent space).
  45806. */
  45807. _this.useObjectSpaceNormalMap = false;
  45808. /**
  45809. * Allows using the bump map in parallax mode.
  45810. */
  45811. _this.useParallax = false;
  45812. /**
  45813. * Allows using the bump map in parallax occlusion mode.
  45814. */
  45815. _this.useParallaxOcclusion = false;
  45816. /**
  45817. * Controls the scale bias of the parallax mode.
  45818. */
  45819. _this.parallaxScaleBias = 0.05;
  45820. /**
  45821. * If sets to true, disables all the lights affecting the material.
  45822. */
  45823. _this.disableLighting = false;
  45824. /**
  45825. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45826. */
  45827. _this.forceIrradianceInFragment = false;
  45828. /**
  45829. * Number of Simultaneous lights allowed on the material.
  45830. */
  45831. _this.maxSimultaneousLights = 4;
  45832. /**
  45833. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45834. */
  45835. _this.invertNormalMapX = false;
  45836. /**
  45837. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45838. */
  45839. _this.invertNormalMapY = false;
  45840. /**
  45841. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45842. */
  45843. _this.twoSidedLighting = false;
  45844. /**
  45845. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45846. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45847. */
  45848. _this.useAlphaFresnel = false;
  45849. /**
  45850. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45851. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45852. */
  45853. _this.useLinearAlphaFresnel = false;
  45854. /**
  45855. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45856. * And/Or occlude the blended part.
  45857. */
  45858. _this.environmentBRDFTexture = null;
  45859. /**
  45860. * Force normal to face away from face.
  45861. */
  45862. _this.forceNormalForward = false;
  45863. /**
  45864. * Enables specular anti aliasing in the PBR shader.
  45865. * It will both interacts on the Geometry for analytical and IBL lighting.
  45866. * It also prefilter the roughness map based on the bump values.
  45867. */
  45868. _this.enableSpecularAntiAliasing = false;
  45869. /**
  45870. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45871. * makes the reflect vector face the model (under horizon).
  45872. */
  45873. _this.useHorizonOcclusion = true;
  45874. /**
  45875. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45876. * too much the area relying on ambient texture to define their ambient occlusion.
  45877. */
  45878. _this.useRadianceOcclusion = true;
  45879. /**
  45880. * If set to true, no lighting calculations will be applied.
  45881. */
  45882. _this.unlit = false;
  45883. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45884. return _this;
  45885. }
  45886. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45887. /**
  45888. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45889. */
  45890. get: function () {
  45891. return this._PBRMATERIAL_OPAQUE;
  45892. },
  45893. enumerable: true,
  45894. configurable: true
  45895. });
  45896. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45897. /**
  45898. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45899. */
  45900. get: function () {
  45901. return this._PBRMATERIAL_ALPHATEST;
  45902. },
  45903. enumerable: true,
  45904. configurable: true
  45905. });
  45906. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45907. /**
  45908. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45909. */
  45910. get: function () {
  45911. return this._PBRMATERIAL_ALPHABLEND;
  45912. },
  45913. enumerable: true,
  45914. configurable: true
  45915. });
  45916. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45917. /**
  45918. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45919. * They are also discarded below the alpha cutoff threshold to improve performances.
  45920. */
  45921. get: function () {
  45922. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45923. },
  45924. enumerable: true,
  45925. configurable: true
  45926. });
  45927. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45928. /**
  45929. * Gets the image processing configuration used either in this material.
  45930. */
  45931. get: function () {
  45932. return this._imageProcessingConfiguration;
  45933. },
  45934. /**
  45935. * Sets the Default image processing configuration used either in the this material.
  45936. *
  45937. * If sets to null, the scene one is in use.
  45938. */
  45939. set: function (value) {
  45940. this._attachImageProcessingConfiguration(value);
  45941. // Ensure the effect will be rebuilt.
  45942. this._markAllSubMeshesAsTexturesDirty();
  45943. },
  45944. enumerable: true,
  45945. configurable: true
  45946. });
  45947. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45948. /**
  45949. * Gets wether the color curves effect is enabled.
  45950. */
  45951. get: function () {
  45952. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45953. },
  45954. /**
  45955. * Sets wether the color curves effect is enabled.
  45956. */
  45957. set: function (value) {
  45958. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45959. },
  45960. enumerable: true,
  45961. configurable: true
  45962. });
  45963. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45964. /**
  45965. * Gets wether the color grading effect is enabled.
  45966. */
  45967. get: function () {
  45968. return this.imageProcessingConfiguration.colorGradingEnabled;
  45969. },
  45970. /**
  45971. * Gets wether the color grading effect is enabled.
  45972. */
  45973. set: function (value) {
  45974. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45975. },
  45976. enumerable: true,
  45977. configurable: true
  45978. });
  45979. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45980. /**
  45981. * Gets wether tonemapping is enabled or not.
  45982. */
  45983. get: function () {
  45984. return this._imageProcessingConfiguration.toneMappingEnabled;
  45985. },
  45986. /**
  45987. * Sets wether tonemapping is enabled or not
  45988. */
  45989. set: function (value) {
  45990. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45991. },
  45992. enumerable: true,
  45993. configurable: true
  45994. });
  45995. ;
  45996. ;
  45997. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45998. /**
  45999. * The camera exposure used on this material.
  46000. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46001. * This corresponds to a photographic exposure.
  46002. */
  46003. get: function () {
  46004. return this._imageProcessingConfiguration.exposure;
  46005. },
  46006. /**
  46007. * The camera exposure used on this material.
  46008. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46009. * This corresponds to a photographic exposure.
  46010. */
  46011. set: function (value) {
  46012. this._imageProcessingConfiguration.exposure = value;
  46013. },
  46014. enumerable: true,
  46015. configurable: true
  46016. });
  46017. ;
  46018. ;
  46019. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46020. /**
  46021. * Gets The camera contrast used on this material.
  46022. */
  46023. get: function () {
  46024. return this._imageProcessingConfiguration.contrast;
  46025. },
  46026. /**
  46027. * Sets The camera contrast used on this material.
  46028. */
  46029. set: function (value) {
  46030. this._imageProcessingConfiguration.contrast = value;
  46031. },
  46032. enumerable: true,
  46033. configurable: true
  46034. });
  46035. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46036. /**
  46037. * Gets the Color Grading 2D Lookup Texture.
  46038. */
  46039. get: function () {
  46040. return this._imageProcessingConfiguration.colorGradingTexture;
  46041. },
  46042. /**
  46043. * Sets the Color Grading 2D Lookup Texture.
  46044. */
  46045. set: function (value) {
  46046. this._imageProcessingConfiguration.colorGradingTexture = value;
  46047. },
  46048. enumerable: true,
  46049. configurable: true
  46050. });
  46051. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46052. /**
  46053. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46054. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46055. * 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;
  46056. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46057. */
  46058. get: function () {
  46059. return this._imageProcessingConfiguration.colorCurves;
  46060. },
  46061. /**
  46062. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46063. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46064. * 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;
  46065. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46066. */
  46067. set: function (value) {
  46068. this._imageProcessingConfiguration.colorCurves = value;
  46069. },
  46070. enumerable: true,
  46071. configurable: true
  46072. });
  46073. /**
  46074. * Returns the name of this material class.
  46075. */
  46076. PBRMaterial.prototype.getClassName = function () {
  46077. return "PBRMaterial";
  46078. };
  46079. /**
  46080. * Returns an array of the actively used textures.
  46081. * @returns - Array of BaseTextures
  46082. */
  46083. PBRMaterial.prototype.getActiveTextures = function () {
  46084. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46085. if (this._albedoTexture) {
  46086. activeTextures.push(this._albedoTexture);
  46087. }
  46088. if (this._ambientTexture) {
  46089. activeTextures.push(this._ambientTexture);
  46090. }
  46091. if (this._opacityTexture) {
  46092. activeTextures.push(this._opacityTexture);
  46093. }
  46094. if (this._reflectionTexture) {
  46095. activeTextures.push(this._reflectionTexture);
  46096. }
  46097. if (this._emissiveTexture) {
  46098. activeTextures.push(this._emissiveTexture);
  46099. }
  46100. if (this._reflectivityTexture) {
  46101. activeTextures.push(this._reflectivityTexture);
  46102. }
  46103. if (this._metallicTexture) {
  46104. activeTextures.push(this._metallicTexture);
  46105. }
  46106. if (this._microSurfaceTexture) {
  46107. activeTextures.push(this._microSurfaceTexture);
  46108. }
  46109. if (this._bumpTexture) {
  46110. activeTextures.push(this._bumpTexture);
  46111. }
  46112. if (this._lightmapTexture) {
  46113. activeTextures.push(this._lightmapTexture);
  46114. }
  46115. if (this._refractionTexture) {
  46116. activeTextures.push(this._refractionTexture);
  46117. }
  46118. return activeTextures;
  46119. };
  46120. /**
  46121. * Checks to see if a texture is used in the material.
  46122. * @param texture - Base texture to use.
  46123. * @returns - Boolean specifying if a texture is used in the material.
  46124. */
  46125. PBRMaterial.prototype.hasTexture = function (texture) {
  46126. if (_super.prototype.hasTexture.call(this, texture)) {
  46127. return true;
  46128. }
  46129. if (this._albedoTexture === texture) {
  46130. return true;
  46131. }
  46132. if (this._ambientTexture === texture) {
  46133. return true;
  46134. }
  46135. if (this._opacityTexture === texture) {
  46136. return true;
  46137. }
  46138. if (this._reflectionTexture === texture) {
  46139. return true;
  46140. }
  46141. if (this._reflectivityTexture === texture) {
  46142. return true;
  46143. }
  46144. if (this._metallicTexture === texture) {
  46145. return true;
  46146. }
  46147. if (this._microSurfaceTexture === texture) {
  46148. return true;
  46149. }
  46150. if (this._bumpTexture === texture) {
  46151. return true;
  46152. }
  46153. if (this._lightmapTexture === texture) {
  46154. return true;
  46155. }
  46156. if (this._refractionTexture === texture) {
  46157. return true;
  46158. }
  46159. return false;
  46160. };
  46161. /**
  46162. * Makes a duplicate of the current material.
  46163. * @param name - name to use for the new material.
  46164. */
  46165. PBRMaterial.prototype.clone = function (name) {
  46166. var _this = this;
  46167. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46168. clone.id = name;
  46169. clone.name = name;
  46170. return clone;
  46171. };
  46172. /**
  46173. * Serializes this PBR Material.
  46174. * @returns - An object with the serialized material.
  46175. */
  46176. PBRMaterial.prototype.serialize = function () {
  46177. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46178. serializationObject.customType = "BABYLON.PBRMaterial";
  46179. return serializationObject;
  46180. };
  46181. // Statics
  46182. /**
  46183. * Parses a PBR Material from a serialized object.
  46184. * @param source - Serialized object.
  46185. * @param scene - BJS scene instance.
  46186. * @param rootUrl - url for the scene object
  46187. * @returns - PBRMaterial
  46188. */
  46189. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46190. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46191. };
  46192. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46193. /**
  46194. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46195. */
  46196. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46197. /**
  46198. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46199. */
  46200. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46201. /**
  46202. * 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.
  46203. * They are also discarded below the alpha cutoff threshold to improve performances.
  46204. */
  46205. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46206. __decorate([
  46207. BABYLON.serialize(),
  46208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46209. ], PBRMaterial.prototype, "directIntensity", void 0);
  46210. __decorate([
  46211. BABYLON.serialize(),
  46212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46213. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46214. __decorate([
  46215. BABYLON.serialize(),
  46216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46217. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46218. __decorate([
  46219. BABYLON.serialize(),
  46220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46221. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46222. __decorate([
  46223. BABYLON.serialize(),
  46224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46225. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46226. __decorate([
  46227. BABYLON.serializeAsTexture(),
  46228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46229. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46230. __decorate([
  46231. BABYLON.serializeAsTexture(),
  46232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46233. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46234. __decorate([
  46235. BABYLON.serialize(),
  46236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46237. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46238. __decorate([
  46239. BABYLON.serializeAsTexture(),
  46240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46241. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46242. __decorate([
  46243. BABYLON.serializeAsTexture(),
  46244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46245. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46246. __decorate([
  46247. BABYLON.serializeAsTexture(),
  46248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46249. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46250. __decorate([
  46251. BABYLON.serializeAsTexture(),
  46252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46253. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46254. __decorate([
  46255. BABYLON.serializeAsTexture(),
  46256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46257. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46258. __decorate([
  46259. BABYLON.serialize(),
  46260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46261. ], PBRMaterial.prototype, "metallic", void 0);
  46262. __decorate([
  46263. BABYLON.serialize(),
  46264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46265. ], PBRMaterial.prototype, "roughness", void 0);
  46266. __decorate([
  46267. BABYLON.serializeAsTexture(),
  46268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46269. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46270. __decorate([
  46271. BABYLON.serializeAsTexture(),
  46272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46273. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46274. __decorate([
  46275. BABYLON.serializeAsTexture(),
  46276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46277. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46278. __decorate([
  46279. BABYLON.serializeAsTexture(),
  46280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46281. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46282. __decorate([
  46283. BABYLON.serializeAsColor3("ambient"),
  46284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46285. ], PBRMaterial.prototype, "ambientColor", void 0);
  46286. __decorate([
  46287. BABYLON.serializeAsColor3("albedo"),
  46288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46289. ], PBRMaterial.prototype, "albedoColor", void 0);
  46290. __decorate([
  46291. BABYLON.serializeAsColor3("reflectivity"),
  46292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46293. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46294. __decorate([
  46295. BABYLON.serializeAsColor3("reflection"),
  46296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46297. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46298. __decorate([
  46299. BABYLON.serializeAsColor3("emissive"),
  46300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46301. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46302. __decorate([
  46303. BABYLON.serialize(),
  46304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46305. ], PBRMaterial.prototype, "microSurface", void 0);
  46306. __decorate([
  46307. BABYLON.serialize(),
  46308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46309. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46310. __decorate([
  46311. BABYLON.serialize(),
  46312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46313. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46314. __decorate([
  46315. BABYLON.serialize(),
  46316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46317. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46318. __decorate([
  46319. BABYLON.serialize(),
  46320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46321. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46322. __decorate([
  46323. BABYLON.serialize(),
  46324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46325. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46326. __decorate([
  46327. BABYLON.serialize(),
  46328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46329. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46330. __decorate([
  46331. BABYLON.serialize(),
  46332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46333. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46334. __decorate([
  46335. BABYLON.serialize(),
  46336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46337. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46338. __decorate([
  46339. BABYLON.serialize(),
  46340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46341. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46342. __decorate([
  46343. BABYLON.serialize(),
  46344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46345. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46346. __decorate([
  46347. BABYLON.serialize(),
  46348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46349. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46350. __decorate([
  46351. BABYLON.serialize(),
  46352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46353. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46354. __decorate([
  46355. BABYLON.serialize(),
  46356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46357. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46358. __decorate([
  46359. BABYLON.serialize(),
  46360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46361. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46362. __decorate([
  46363. BABYLON.serialize(),
  46364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46365. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46366. __decorate([
  46367. BABYLON.serialize(),
  46368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46369. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46370. __decorate([
  46371. BABYLON.serialize(),
  46372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46373. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46374. __decorate([
  46375. BABYLON.serialize(),
  46376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46377. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46378. __decorate([
  46379. BABYLON.serialize(),
  46380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46381. ], PBRMaterial.prototype, "useParallax", void 0);
  46382. __decorate([
  46383. BABYLON.serialize(),
  46384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46385. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46386. __decorate([
  46387. BABYLON.serialize(),
  46388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46389. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46390. __decorate([
  46391. BABYLON.serialize(),
  46392. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46393. ], PBRMaterial.prototype, "disableLighting", void 0);
  46394. __decorate([
  46395. BABYLON.serialize(),
  46396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46397. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46398. __decorate([
  46399. BABYLON.serialize(),
  46400. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46401. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46402. __decorate([
  46403. BABYLON.serialize(),
  46404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46405. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46406. __decorate([
  46407. BABYLON.serialize(),
  46408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46409. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46410. __decorate([
  46411. BABYLON.serialize(),
  46412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46413. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46414. __decorate([
  46415. BABYLON.serialize(),
  46416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46417. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46418. __decorate([
  46419. BABYLON.serialize(),
  46420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46421. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46422. __decorate([
  46423. BABYLON.serializeAsTexture(),
  46424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46425. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46426. __decorate([
  46427. BABYLON.serialize(),
  46428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46429. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46430. __decorate([
  46431. BABYLON.serialize(),
  46432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46433. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46434. __decorate([
  46435. BABYLON.serialize(),
  46436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46437. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46438. __decorate([
  46439. BABYLON.serialize(),
  46440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46441. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46442. __decorate([
  46443. BABYLON.serialize(),
  46444. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46445. ], PBRMaterial.prototype, "unlit", void 0);
  46446. return PBRMaterial;
  46447. }(BABYLON.PBRBaseMaterial));
  46448. BABYLON.PBRMaterial = PBRMaterial;
  46449. })(BABYLON || (BABYLON = {}));
  46450. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46451. var BABYLON;
  46452. (function (BABYLON) {
  46453. /**
  46454. * The PBR material of BJS following the metal roughness convention.
  46455. *
  46456. * This fits to the PBR convention in the GLTF definition:
  46457. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46458. */
  46459. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46460. __extends(PBRMetallicRoughnessMaterial, _super);
  46461. /**
  46462. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46463. *
  46464. * @param name The material name
  46465. * @param scene The scene the material will be use in.
  46466. */
  46467. function PBRMetallicRoughnessMaterial(name, scene) {
  46468. var _this = _super.call(this, name, scene) || this;
  46469. _this._useRoughnessFromMetallicTextureAlpha = false;
  46470. _this._useRoughnessFromMetallicTextureGreen = true;
  46471. _this._useMetallnessFromMetallicTextureBlue = true;
  46472. _this.metallic = 1.0;
  46473. _this.roughness = 1.0;
  46474. return _this;
  46475. }
  46476. /**
  46477. * Return the currrent class name of the material.
  46478. */
  46479. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46480. return "PBRMetallicRoughnessMaterial";
  46481. };
  46482. /**
  46483. * Return the active textures of the material.
  46484. */
  46485. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46486. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46487. if (this.baseTexture) {
  46488. activeTextures.push(this.baseTexture);
  46489. }
  46490. if (this.metallicRoughnessTexture) {
  46491. activeTextures.push(this.metallicRoughnessTexture);
  46492. }
  46493. return activeTextures;
  46494. };
  46495. /**
  46496. * Checks to see if a texture is used in the material.
  46497. * @param texture - Base texture to use.
  46498. * @returns - Boolean specifying if a texture is used in the material.
  46499. */
  46500. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46501. if (_super.prototype.hasTexture.call(this, texture)) {
  46502. return true;
  46503. }
  46504. if (this.baseTexture === texture) {
  46505. return true;
  46506. }
  46507. if (this.metallicRoughnessTexture === texture) {
  46508. return true;
  46509. }
  46510. return false;
  46511. };
  46512. /**
  46513. * Makes a duplicate of the current material.
  46514. * @param name - name to use for the new material.
  46515. */
  46516. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46517. var _this = this;
  46518. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46519. clone.id = name;
  46520. clone.name = name;
  46521. return clone;
  46522. };
  46523. /**
  46524. * Serialize the material to a parsable JSON object.
  46525. */
  46526. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46527. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46528. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46529. return serializationObject;
  46530. };
  46531. /**
  46532. * Parses a JSON object correponding to the serialize function.
  46533. */
  46534. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46535. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46536. };
  46537. __decorate([
  46538. BABYLON.serializeAsColor3(),
  46539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46540. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46541. __decorate([
  46542. BABYLON.serializeAsTexture(),
  46543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46544. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46545. __decorate([
  46546. BABYLON.serialize(),
  46547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46548. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46549. __decorate([
  46550. BABYLON.serialize(),
  46551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46552. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46553. __decorate([
  46554. BABYLON.serializeAsTexture(),
  46555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46556. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46557. return PBRMetallicRoughnessMaterial;
  46558. }(BABYLON.PBRBaseSimpleMaterial));
  46559. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46560. })(BABYLON || (BABYLON = {}));
  46561. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46562. var BABYLON;
  46563. (function (BABYLON) {
  46564. /**
  46565. * The PBR material of BJS following the specular glossiness convention.
  46566. *
  46567. * This fits to the PBR convention in the GLTF definition:
  46568. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46569. */
  46570. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46571. __extends(PBRSpecularGlossinessMaterial, _super);
  46572. /**
  46573. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46574. *
  46575. * @param name The material name
  46576. * @param scene The scene the material will be use in.
  46577. */
  46578. function PBRSpecularGlossinessMaterial(name, scene) {
  46579. var _this = _super.call(this, name, scene) || this;
  46580. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46581. return _this;
  46582. }
  46583. /**
  46584. * Return the currrent class name of the material.
  46585. */
  46586. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46587. return "PBRSpecularGlossinessMaterial";
  46588. };
  46589. /**
  46590. * Return the active textures of the material.
  46591. */
  46592. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46593. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46594. if (this.diffuseTexture) {
  46595. activeTextures.push(this.diffuseTexture);
  46596. }
  46597. if (this.specularGlossinessTexture) {
  46598. activeTextures.push(this.specularGlossinessTexture);
  46599. }
  46600. return activeTextures;
  46601. };
  46602. /**
  46603. * Checks to see if a texture is used in the material.
  46604. * @param texture - Base texture to use.
  46605. * @returns - Boolean specifying if a texture is used in the material.
  46606. */
  46607. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46608. if (_super.prototype.hasTexture.call(this, texture)) {
  46609. return true;
  46610. }
  46611. if (this.diffuseTexture === texture) {
  46612. return true;
  46613. }
  46614. if (this.specularGlossinessTexture === texture) {
  46615. return true;
  46616. }
  46617. return false;
  46618. };
  46619. /**
  46620. * Makes a duplicate of the current material.
  46621. * @param name - name to use for the new material.
  46622. */
  46623. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46624. var _this = this;
  46625. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46626. clone.id = name;
  46627. clone.name = name;
  46628. return clone;
  46629. };
  46630. /**
  46631. * Serialize the material to a parsable JSON object.
  46632. */
  46633. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46634. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46635. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46636. return serializationObject;
  46637. };
  46638. /**
  46639. * Parses a JSON object correponding to the serialize function.
  46640. */
  46641. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46642. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46643. };
  46644. __decorate([
  46645. BABYLON.serializeAsColor3("diffuse"),
  46646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46647. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46648. __decorate([
  46649. BABYLON.serializeAsTexture(),
  46650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46651. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46652. __decorate([
  46653. BABYLON.serializeAsColor3("specular"),
  46654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46655. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46656. __decorate([
  46657. BABYLON.serialize(),
  46658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46659. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46660. __decorate([
  46661. BABYLON.serializeAsTexture(),
  46662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46663. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46664. return PBRSpecularGlossinessMaterial;
  46665. }(BABYLON.PBRBaseSimpleMaterial));
  46666. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46667. })(BABYLON || (BABYLON = {}));
  46668. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46669. var BABYLON;
  46670. (function (BABYLON) {
  46671. BABYLON.CameraInputTypes = {};
  46672. var CameraInputsManager = /** @class */ (function () {
  46673. function CameraInputsManager(camera) {
  46674. this.attached = {};
  46675. this.camera = camera;
  46676. this.checkInputs = function () { };
  46677. }
  46678. /**
  46679. * Add an input method to a camera.
  46680. * builtin inputs example: camera.inputs.addGamepad();
  46681. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46682. * @param input camera input method
  46683. */
  46684. CameraInputsManager.prototype.add = function (input) {
  46685. var type = input.getSimpleName();
  46686. if (this.attached[type]) {
  46687. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46688. return;
  46689. }
  46690. this.attached[type] = input;
  46691. input.camera = this.camera;
  46692. //for checkInputs, we are dynamically creating a function
  46693. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46694. if (input.checkInputs) {
  46695. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46696. }
  46697. if (this.attachedElement) {
  46698. input.attachControl(this.attachedElement);
  46699. }
  46700. };
  46701. /**
  46702. * Remove a specific input method from a camera
  46703. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46704. * @param inputToRemove camera input method
  46705. */
  46706. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46707. for (var cam in this.attached) {
  46708. var input = this.attached[cam];
  46709. if (input === inputToRemove) {
  46710. input.detachControl(this.attachedElement);
  46711. input.camera = null;
  46712. delete this.attached[cam];
  46713. this.rebuildInputCheck();
  46714. }
  46715. }
  46716. };
  46717. CameraInputsManager.prototype.removeByType = function (inputType) {
  46718. for (var cam in this.attached) {
  46719. var input = this.attached[cam];
  46720. if (input.getClassName() === inputType) {
  46721. input.detachControl(this.attachedElement);
  46722. input.camera = null;
  46723. delete this.attached[cam];
  46724. this.rebuildInputCheck();
  46725. }
  46726. }
  46727. };
  46728. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46729. var current = this.checkInputs;
  46730. return function () {
  46731. current();
  46732. fn();
  46733. };
  46734. };
  46735. CameraInputsManager.prototype.attachInput = function (input) {
  46736. if (this.attachedElement) {
  46737. input.attachControl(this.attachedElement, this.noPreventDefault);
  46738. }
  46739. };
  46740. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46741. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46742. if (this.attachedElement) {
  46743. return;
  46744. }
  46745. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46746. this.attachedElement = element;
  46747. this.noPreventDefault = noPreventDefault;
  46748. for (var cam in this.attached) {
  46749. this.attached[cam].attachControl(element, noPreventDefault);
  46750. }
  46751. };
  46752. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46753. if (disconnect === void 0) { disconnect = false; }
  46754. if (this.attachedElement !== element) {
  46755. return;
  46756. }
  46757. for (var cam in this.attached) {
  46758. this.attached[cam].detachControl(element);
  46759. if (disconnect) {
  46760. this.attached[cam].camera = null;
  46761. }
  46762. }
  46763. this.attachedElement = null;
  46764. };
  46765. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46766. this.checkInputs = function () { };
  46767. for (var cam in this.attached) {
  46768. var input = this.attached[cam];
  46769. if (input.checkInputs) {
  46770. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46771. }
  46772. }
  46773. };
  46774. /**
  46775. * Remove all attached input methods from a camera
  46776. */
  46777. CameraInputsManager.prototype.clear = function () {
  46778. if (this.attachedElement) {
  46779. this.detachElement(this.attachedElement, true);
  46780. }
  46781. this.attached = {};
  46782. this.attachedElement = null;
  46783. this.checkInputs = function () { };
  46784. };
  46785. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46786. var inputs = {};
  46787. for (var cam in this.attached) {
  46788. var input = this.attached[cam];
  46789. var res = BABYLON.SerializationHelper.Serialize(input);
  46790. inputs[input.getClassName()] = res;
  46791. }
  46792. serializedCamera.inputsmgr = inputs;
  46793. };
  46794. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46795. var parsedInputs = parsedCamera.inputsmgr;
  46796. if (parsedInputs) {
  46797. this.clear();
  46798. for (var n in parsedInputs) {
  46799. var construct = BABYLON.CameraInputTypes[n];
  46800. if (construct) {
  46801. var parsedinput = parsedInputs[n];
  46802. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46803. this.add(input);
  46804. }
  46805. }
  46806. }
  46807. else {
  46808. //2016-03-08 this part is for managing backward compatibility
  46809. for (var n in this.attached) {
  46810. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46811. if (construct) {
  46812. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46813. this.remove(this.attached[n]);
  46814. this.add(input);
  46815. }
  46816. }
  46817. }
  46818. };
  46819. return CameraInputsManager;
  46820. }());
  46821. BABYLON.CameraInputsManager = CameraInputsManager;
  46822. })(BABYLON || (BABYLON = {}));
  46823. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46824. var BABYLON;
  46825. (function (BABYLON) {
  46826. var TargetCamera = /** @class */ (function (_super) {
  46827. __extends(TargetCamera, _super);
  46828. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46829. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46830. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46831. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46832. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46833. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46834. _this.speed = 2.0;
  46835. _this.noRotationConstraint = false;
  46836. _this.lockedTarget = null;
  46837. _this._currentTarget = BABYLON.Vector3.Zero();
  46838. _this._viewMatrix = BABYLON.Matrix.Zero();
  46839. _this._camMatrix = BABYLON.Matrix.Zero();
  46840. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46841. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46842. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46843. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46844. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46845. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46846. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46847. return _this;
  46848. }
  46849. TargetCamera.prototype.getFrontPosition = function (distance) {
  46850. this.getWorldMatrix();
  46851. var direction = this.getTarget().subtract(this.position);
  46852. direction.normalize();
  46853. direction.scaleInPlace(distance);
  46854. return this.globalPosition.add(direction);
  46855. };
  46856. TargetCamera.prototype._getLockedTargetPosition = function () {
  46857. if (!this.lockedTarget) {
  46858. return null;
  46859. }
  46860. if (this.lockedTarget.absolutePosition) {
  46861. this.lockedTarget.computeWorldMatrix();
  46862. }
  46863. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46864. };
  46865. TargetCamera.prototype.storeState = function () {
  46866. this._storedPosition = this.position.clone();
  46867. this._storedRotation = this.rotation.clone();
  46868. if (this.rotationQuaternion) {
  46869. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46870. }
  46871. return _super.prototype.storeState.call(this);
  46872. };
  46873. /**
  46874. * Restored camera state. You must call storeState() first
  46875. */
  46876. TargetCamera.prototype._restoreStateValues = function () {
  46877. if (!_super.prototype._restoreStateValues.call(this)) {
  46878. return false;
  46879. }
  46880. this.position = this._storedPosition.clone();
  46881. this.rotation = this._storedRotation.clone();
  46882. if (this.rotationQuaternion) {
  46883. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46884. }
  46885. this.cameraDirection.copyFromFloats(0, 0, 0);
  46886. this.cameraRotation.copyFromFloats(0, 0);
  46887. return true;
  46888. };
  46889. // Cache
  46890. TargetCamera.prototype._initCache = function () {
  46891. _super.prototype._initCache.call(this);
  46892. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46893. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46894. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46895. };
  46896. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46897. if (!ignoreParentClass) {
  46898. _super.prototype._updateCache.call(this);
  46899. }
  46900. var lockedTargetPosition = this._getLockedTargetPosition();
  46901. if (!lockedTargetPosition) {
  46902. this._cache.lockedTarget = null;
  46903. }
  46904. else {
  46905. if (!this._cache.lockedTarget) {
  46906. this._cache.lockedTarget = lockedTargetPosition.clone();
  46907. }
  46908. else {
  46909. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46910. }
  46911. }
  46912. this._cache.rotation.copyFrom(this.rotation);
  46913. if (this.rotationQuaternion)
  46914. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46915. };
  46916. // Synchronized
  46917. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46918. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46919. return false;
  46920. }
  46921. var lockedTargetPosition = this._getLockedTargetPosition();
  46922. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46923. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46924. };
  46925. // Methods
  46926. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46927. var engine = this.getEngine();
  46928. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46929. };
  46930. // Target
  46931. TargetCamera.prototype.setTarget = function (target) {
  46932. this.upVector.normalize();
  46933. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46934. this._camMatrix.invert();
  46935. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46936. var vDir = target.subtract(this.position);
  46937. if (vDir.x >= 0.0) {
  46938. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46939. }
  46940. else {
  46941. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46942. }
  46943. this.rotation.z = 0;
  46944. if (isNaN(this.rotation.x)) {
  46945. this.rotation.x = 0;
  46946. }
  46947. if (isNaN(this.rotation.y)) {
  46948. this.rotation.y = 0;
  46949. }
  46950. if (isNaN(this.rotation.z)) {
  46951. this.rotation.z = 0;
  46952. }
  46953. if (this.rotationQuaternion) {
  46954. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46955. }
  46956. };
  46957. /**
  46958. * Return the current target position of the camera. This value is expressed in local space.
  46959. */
  46960. TargetCamera.prototype.getTarget = function () {
  46961. return this._currentTarget;
  46962. };
  46963. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46964. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46965. };
  46966. TargetCamera.prototype._updatePosition = function () {
  46967. if (this.parent) {
  46968. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46969. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46970. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46971. return;
  46972. }
  46973. this.position.addInPlace(this.cameraDirection);
  46974. };
  46975. TargetCamera.prototype._checkInputs = function () {
  46976. var needToMove = this._decideIfNeedsToMove();
  46977. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46978. // Move
  46979. if (needToMove) {
  46980. this._updatePosition();
  46981. }
  46982. // Rotate
  46983. if (needToRotate) {
  46984. this.rotation.x += this.cameraRotation.x;
  46985. this.rotation.y += this.cameraRotation.y;
  46986. //rotate, if quaternion is set and rotation was used
  46987. if (this.rotationQuaternion) {
  46988. var len = this.rotation.lengthSquared();
  46989. if (len) {
  46990. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46991. }
  46992. }
  46993. if (!this.noRotationConstraint) {
  46994. var limit = (Math.PI / 2) * 0.95;
  46995. if (this.rotation.x > limit)
  46996. this.rotation.x = limit;
  46997. if (this.rotation.x < -limit)
  46998. this.rotation.x = -limit;
  46999. }
  47000. }
  47001. // Inertia
  47002. if (needToMove) {
  47003. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47004. this.cameraDirection.x = 0;
  47005. }
  47006. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47007. this.cameraDirection.y = 0;
  47008. }
  47009. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47010. this.cameraDirection.z = 0;
  47011. }
  47012. this.cameraDirection.scaleInPlace(this.inertia);
  47013. }
  47014. if (needToRotate) {
  47015. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47016. this.cameraRotation.x = 0;
  47017. }
  47018. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47019. this.cameraRotation.y = 0;
  47020. }
  47021. this.cameraRotation.scaleInPlace(this.inertia);
  47022. }
  47023. _super.prototype._checkInputs.call(this);
  47024. };
  47025. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47026. if (this.rotationQuaternion) {
  47027. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47028. }
  47029. else {
  47030. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47031. }
  47032. //update the up vector!
  47033. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47034. };
  47035. TargetCamera.prototype._getViewMatrix = function () {
  47036. if (this.lockedTarget) {
  47037. this.setTarget(this._getLockedTargetPosition());
  47038. }
  47039. // Compute
  47040. this._updateCameraRotationMatrix();
  47041. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47042. // Computing target and final matrix
  47043. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47044. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47045. return this._viewMatrix;
  47046. };
  47047. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47048. if (this.parent) {
  47049. var parentWorldMatrix = this.parent.getWorldMatrix();
  47050. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47051. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47052. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47053. this._markSyncedWithParent();
  47054. }
  47055. else {
  47056. this._globalPosition.copyFrom(this.position);
  47057. this._globalCurrentTarget.copyFrom(target);
  47058. this._globalCurrentUpVector.copyFrom(up);
  47059. }
  47060. if (this.getScene().useRightHandedSystem) {
  47061. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47062. }
  47063. else {
  47064. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47065. }
  47066. };
  47067. /**
  47068. * @override
  47069. * Override Camera.createRigCamera
  47070. */
  47071. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47072. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47073. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47074. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47075. if (!this.rotationQuaternion) {
  47076. this.rotationQuaternion = new BABYLON.Quaternion();
  47077. }
  47078. rigCamera._cameraRigParams = {};
  47079. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47080. }
  47081. return rigCamera;
  47082. }
  47083. return null;
  47084. };
  47085. /**
  47086. * @override
  47087. * Override Camera._updateRigCameras
  47088. */
  47089. TargetCamera.prototype._updateRigCameras = function () {
  47090. var camLeft = this._rigCameras[0];
  47091. var camRight = this._rigCameras[1];
  47092. switch (this.cameraRigMode) {
  47093. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47094. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47095. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47096. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47097. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47098. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47099. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47100. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47101. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47102. camLeft.setTarget(this.getTarget());
  47103. camRight.setTarget(this.getTarget());
  47104. break;
  47105. case BABYLON.Camera.RIG_MODE_VR:
  47106. if (camLeft.rotationQuaternion) {
  47107. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47108. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47109. }
  47110. else {
  47111. camLeft.rotation.copyFrom(this.rotation);
  47112. camRight.rotation.copyFrom(this.rotation);
  47113. }
  47114. camLeft.position.copyFrom(this.position);
  47115. camRight.position.copyFrom(this.position);
  47116. break;
  47117. }
  47118. _super.prototype._updateRigCameras.call(this);
  47119. };
  47120. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47121. if (!this._rigCamTransformMatrix) {
  47122. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47123. }
  47124. var target = this.getTarget();
  47125. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47126. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47127. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47128. };
  47129. TargetCamera.prototype.getClassName = function () {
  47130. return "TargetCamera";
  47131. };
  47132. __decorate([
  47133. BABYLON.serializeAsVector3()
  47134. ], TargetCamera.prototype, "rotation", void 0);
  47135. __decorate([
  47136. BABYLON.serialize()
  47137. ], TargetCamera.prototype, "speed", void 0);
  47138. __decorate([
  47139. BABYLON.serializeAsMeshReference("lockedTargetId")
  47140. ], TargetCamera.prototype, "lockedTarget", void 0);
  47141. return TargetCamera;
  47142. }(BABYLON.Camera));
  47143. BABYLON.TargetCamera = TargetCamera;
  47144. })(BABYLON || (BABYLON = {}));
  47145. //# sourceMappingURL=babylon.targetCamera.js.map
  47146. var BABYLON;
  47147. (function (BABYLON) {
  47148. var FreeCameraMouseInput = /** @class */ (function () {
  47149. function FreeCameraMouseInput(touchEnabled) {
  47150. if (touchEnabled === void 0) { touchEnabled = true; }
  47151. this.touchEnabled = touchEnabled;
  47152. this.buttons = [0, 1, 2];
  47153. this.angularSensibility = 2000.0;
  47154. this.previousPosition = null;
  47155. }
  47156. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47157. var _this = this;
  47158. var engine = this.camera.getEngine();
  47159. if (!this._pointerInput) {
  47160. this._pointerInput = function (p, s) {
  47161. var evt = p.event;
  47162. if (engine.isInVRExclusivePointerMode) {
  47163. return;
  47164. }
  47165. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47166. return;
  47167. }
  47168. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47169. return;
  47170. }
  47171. var srcElement = (evt.srcElement || evt.target);
  47172. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47173. try {
  47174. srcElement.setPointerCapture(evt.pointerId);
  47175. }
  47176. catch (e) {
  47177. //Nothing to do with the error. Execution will continue.
  47178. }
  47179. _this.previousPosition = {
  47180. x: evt.clientX,
  47181. y: evt.clientY
  47182. };
  47183. if (!noPreventDefault) {
  47184. evt.preventDefault();
  47185. element.focus();
  47186. }
  47187. }
  47188. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47189. try {
  47190. srcElement.releasePointerCapture(evt.pointerId);
  47191. }
  47192. catch (e) {
  47193. //Nothing to do with the error.
  47194. }
  47195. _this.previousPosition = null;
  47196. if (!noPreventDefault) {
  47197. evt.preventDefault();
  47198. }
  47199. }
  47200. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47201. if (!_this.previousPosition || engine.isPointerLock) {
  47202. return;
  47203. }
  47204. var offsetX = evt.clientX - _this.previousPosition.x;
  47205. if (_this.camera.getScene().useRightHandedSystem)
  47206. offsetX *= -1;
  47207. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47208. offsetX *= -1;
  47209. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47210. var offsetY = evt.clientY - _this.previousPosition.y;
  47211. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47212. _this.previousPosition = {
  47213. x: evt.clientX,
  47214. y: evt.clientY
  47215. };
  47216. if (!noPreventDefault) {
  47217. evt.preventDefault();
  47218. }
  47219. }
  47220. };
  47221. }
  47222. this._onMouseMove = function (evt) {
  47223. if (!engine.isPointerLock) {
  47224. return;
  47225. }
  47226. if (engine.isInVRExclusivePointerMode) {
  47227. return;
  47228. }
  47229. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47230. if (_this.camera.getScene().useRightHandedSystem)
  47231. offsetX *= -1;
  47232. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47233. offsetX *= -1;
  47234. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47235. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47236. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47237. _this.previousPosition = null;
  47238. if (!noPreventDefault) {
  47239. evt.preventDefault();
  47240. }
  47241. };
  47242. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47243. element.addEventListener("mousemove", this._onMouseMove, false);
  47244. };
  47245. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47246. if (this._observer && element) {
  47247. this.camera.getScene().onPointerObservable.remove(this._observer);
  47248. if (this._onMouseMove) {
  47249. element.removeEventListener("mousemove", this._onMouseMove);
  47250. }
  47251. this._observer = null;
  47252. this._onMouseMove = null;
  47253. this.previousPosition = null;
  47254. }
  47255. };
  47256. FreeCameraMouseInput.prototype.getClassName = function () {
  47257. return "FreeCameraMouseInput";
  47258. };
  47259. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47260. return "mouse";
  47261. };
  47262. __decorate([
  47263. BABYLON.serialize()
  47264. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47265. __decorate([
  47266. BABYLON.serialize()
  47267. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47268. return FreeCameraMouseInput;
  47269. }());
  47270. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47271. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47272. })(BABYLON || (BABYLON = {}));
  47273. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47274. var BABYLON;
  47275. (function (BABYLON) {
  47276. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47277. function FreeCameraKeyboardMoveInput() {
  47278. this._keys = new Array();
  47279. this.keysUp = [38];
  47280. this.keysDown = [40];
  47281. this.keysLeft = [37];
  47282. this.keysRight = [39];
  47283. }
  47284. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47285. var _this = this;
  47286. if (this._onCanvasBlurObserver) {
  47287. return;
  47288. }
  47289. this._scene = this.camera.getScene();
  47290. this._engine = this._scene.getEngine();
  47291. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47292. _this._keys = [];
  47293. });
  47294. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47295. var evt = info.event;
  47296. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47297. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47298. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47299. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47300. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47301. var index = _this._keys.indexOf(evt.keyCode);
  47302. if (index === -1) {
  47303. _this._keys.push(evt.keyCode);
  47304. }
  47305. if (!noPreventDefault) {
  47306. evt.preventDefault();
  47307. }
  47308. }
  47309. }
  47310. else {
  47311. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47312. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47313. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47314. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47315. var index = _this._keys.indexOf(evt.keyCode);
  47316. if (index >= 0) {
  47317. _this._keys.splice(index, 1);
  47318. }
  47319. if (!noPreventDefault) {
  47320. evt.preventDefault();
  47321. }
  47322. }
  47323. }
  47324. });
  47325. };
  47326. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47327. if (this._scene) {
  47328. if (this._onKeyboardObserver) {
  47329. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47330. }
  47331. if (this._onCanvasBlurObserver) {
  47332. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47333. }
  47334. this._onKeyboardObserver = null;
  47335. this._onCanvasBlurObserver = null;
  47336. }
  47337. this._keys = [];
  47338. };
  47339. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47340. if (this._onKeyboardObserver) {
  47341. var camera = this.camera;
  47342. // Keyboard
  47343. for (var index = 0; index < this._keys.length; index++) {
  47344. var keyCode = this._keys[index];
  47345. var speed = camera._computeLocalCameraSpeed();
  47346. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47347. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47348. }
  47349. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47350. camera._localDirection.copyFromFloats(0, 0, speed);
  47351. }
  47352. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47353. camera._localDirection.copyFromFloats(speed, 0, 0);
  47354. }
  47355. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47356. camera._localDirection.copyFromFloats(0, 0, -speed);
  47357. }
  47358. if (camera.getScene().useRightHandedSystem) {
  47359. camera._localDirection.z *= -1;
  47360. }
  47361. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47362. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47363. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47364. }
  47365. }
  47366. };
  47367. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47368. return "FreeCameraKeyboardMoveInput";
  47369. };
  47370. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47371. this._keys = [];
  47372. };
  47373. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47374. return "keyboard";
  47375. };
  47376. __decorate([
  47377. BABYLON.serialize()
  47378. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47379. __decorate([
  47380. BABYLON.serialize()
  47381. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47382. __decorate([
  47383. BABYLON.serialize()
  47384. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47385. __decorate([
  47386. BABYLON.serialize()
  47387. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47388. return FreeCameraKeyboardMoveInput;
  47389. }());
  47390. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47391. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47392. })(BABYLON || (BABYLON = {}));
  47393. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47394. var BABYLON;
  47395. (function (BABYLON) {
  47396. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47397. __extends(FreeCameraInputsManager, _super);
  47398. function FreeCameraInputsManager(camera) {
  47399. return _super.call(this, camera) || this;
  47400. }
  47401. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47402. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47403. return this;
  47404. };
  47405. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47406. if (touchEnabled === void 0) { touchEnabled = true; }
  47407. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47408. return this;
  47409. };
  47410. FreeCameraInputsManager.prototype.addGamepad = function () {
  47411. this.add(new BABYLON.FreeCameraGamepadInput());
  47412. return this;
  47413. };
  47414. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47415. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47416. return this;
  47417. };
  47418. FreeCameraInputsManager.prototype.addTouch = function () {
  47419. this.add(new BABYLON.FreeCameraTouchInput());
  47420. return this;
  47421. };
  47422. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47423. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47424. return this;
  47425. };
  47426. return FreeCameraInputsManager;
  47427. }(BABYLON.CameraInputsManager));
  47428. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47429. })(BABYLON || (BABYLON = {}));
  47430. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47431. var BABYLON;
  47432. (function (BABYLON) {
  47433. var FreeCamera = /** @class */ (function (_super) {
  47434. __extends(FreeCamera, _super);
  47435. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47436. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47437. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47438. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47439. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47440. _this.checkCollisions = false;
  47441. _this.applyGravity = false;
  47442. _this._needMoveForGravity = false;
  47443. _this._oldPosition = BABYLON.Vector3.Zero();
  47444. _this._diffPosition = BABYLON.Vector3.Zero();
  47445. _this._newPosition = BABYLON.Vector3.Zero();
  47446. // Collisions
  47447. _this._collisionMask = -1;
  47448. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47449. if (collidedMesh === void 0) { collidedMesh = null; }
  47450. //TODO move this to the collision coordinator!
  47451. if (_this.getScene().workerCollisions)
  47452. newPosition.multiplyInPlace(_this._collider._radius);
  47453. var updatePosition = function (newPos) {
  47454. _this._newPosition.copyFrom(newPos);
  47455. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47456. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47457. _this.position.addInPlace(_this._diffPosition);
  47458. if (_this.onCollide && collidedMesh) {
  47459. _this.onCollide(collidedMesh);
  47460. }
  47461. }
  47462. };
  47463. updatePosition(newPosition);
  47464. };
  47465. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47466. _this.inputs.addKeyboard().addMouse();
  47467. return _this;
  47468. }
  47469. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47470. //-- begin properties for backward compatibility for inputs
  47471. /**
  47472. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47473. * Higher values reduce sensitivity.
  47474. */
  47475. get: function () {
  47476. var mouse = this.inputs.attached["mouse"];
  47477. if (mouse)
  47478. return mouse.angularSensibility;
  47479. return 0;
  47480. },
  47481. /**
  47482. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47483. * Higher values reduce sensitivity.
  47484. */
  47485. set: function (value) {
  47486. var mouse = this.inputs.attached["mouse"];
  47487. if (mouse)
  47488. mouse.angularSensibility = value;
  47489. },
  47490. enumerable: true,
  47491. configurable: true
  47492. });
  47493. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47494. get: function () {
  47495. var keyboard = this.inputs.attached["keyboard"];
  47496. if (keyboard)
  47497. return keyboard.keysUp;
  47498. return [];
  47499. },
  47500. set: function (value) {
  47501. var keyboard = this.inputs.attached["keyboard"];
  47502. if (keyboard)
  47503. keyboard.keysUp = value;
  47504. },
  47505. enumerable: true,
  47506. configurable: true
  47507. });
  47508. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47509. get: function () {
  47510. var keyboard = this.inputs.attached["keyboard"];
  47511. if (keyboard)
  47512. return keyboard.keysDown;
  47513. return [];
  47514. },
  47515. set: function (value) {
  47516. var keyboard = this.inputs.attached["keyboard"];
  47517. if (keyboard)
  47518. keyboard.keysDown = value;
  47519. },
  47520. enumerable: true,
  47521. configurable: true
  47522. });
  47523. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47524. get: function () {
  47525. var keyboard = this.inputs.attached["keyboard"];
  47526. if (keyboard)
  47527. return keyboard.keysLeft;
  47528. return [];
  47529. },
  47530. set: function (value) {
  47531. var keyboard = this.inputs.attached["keyboard"];
  47532. if (keyboard)
  47533. keyboard.keysLeft = value;
  47534. },
  47535. enumerable: true,
  47536. configurable: true
  47537. });
  47538. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47539. get: function () {
  47540. var keyboard = this.inputs.attached["keyboard"];
  47541. if (keyboard)
  47542. return keyboard.keysRight;
  47543. return [];
  47544. },
  47545. set: function (value) {
  47546. var keyboard = this.inputs.attached["keyboard"];
  47547. if (keyboard)
  47548. keyboard.keysRight = value;
  47549. },
  47550. enumerable: true,
  47551. configurable: true
  47552. });
  47553. // Controls
  47554. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47555. this.inputs.attachElement(element, noPreventDefault);
  47556. };
  47557. FreeCamera.prototype.detachControl = function (element) {
  47558. this.inputs.detachElement(element);
  47559. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47560. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47561. };
  47562. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47563. get: function () {
  47564. return this._collisionMask;
  47565. },
  47566. set: function (mask) {
  47567. this._collisionMask = !isNaN(mask) ? mask : -1;
  47568. },
  47569. enumerable: true,
  47570. configurable: true
  47571. });
  47572. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47573. var globalPosition;
  47574. if (this.parent) {
  47575. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47576. }
  47577. else {
  47578. globalPosition = this.position;
  47579. }
  47580. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47581. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47582. if (!this._collider) {
  47583. this._collider = new BABYLON.Collider();
  47584. }
  47585. this._collider._radius = this.ellipsoid;
  47586. this._collider.collisionMask = this._collisionMask;
  47587. //no need for clone, as long as gravity is not on.
  47588. var actualDisplacement = displacement;
  47589. //add gravity to the direction to prevent the dual-collision checking
  47590. if (this.applyGravity) {
  47591. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47592. actualDisplacement = displacement.add(this.getScene().gravity);
  47593. }
  47594. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47595. };
  47596. FreeCamera.prototype._checkInputs = function () {
  47597. if (!this._localDirection) {
  47598. this._localDirection = BABYLON.Vector3.Zero();
  47599. this._transformedDirection = BABYLON.Vector3.Zero();
  47600. }
  47601. this.inputs.checkInputs();
  47602. _super.prototype._checkInputs.call(this);
  47603. };
  47604. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47605. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47606. };
  47607. FreeCamera.prototype._updatePosition = function () {
  47608. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47609. this._collideWithWorld(this.cameraDirection);
  47610. }
  47611. else {
  47612. _super.prototype._updatePosition.call(this);
  47613. }
  47614. };
  47615. FreeCamera.prototype.dispose = function () {
  47616. this.inputs.clear();
  47617. _super.prototype.dispose.call(this);
  47618. };
  47619. FreeCamera.prototype.getClassName = function () {
  47620. return "FreeCamera";
  47621. };
  47622. __decorate([
  47623. BABYLON.serializeAsVector3()
  47624. ], FreeCamera.prototype, "ellipsoid", void 0);
  47625. __decorate([
  47626. BABYLON.serializeAsVector3()
  47627. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47628. __decorate([
  47629. BABYLON.serialize()
  47630. ], FreeCamera.prototype, "checkCollisions", void 0);
  47631. __decorate([
  47632. BABYLON.serialize()
  47633. ], FreeCamera.prototype, "applyGravity", void 0);
  47634. return FreeCamera;
  47635. }(BABYLON.TargetCamera));
  47636. BABYLON.FreeCamera = FreeCamera;
  47637. })(BABYLON || (BABYLON = {}));
  47638. //# sourceMappingURL=babylon.freeCamera.js.map
  47639. var BABYLON;
  47640. (function (BABYLON) {
  47641. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47642. function ArcRotateCameraKeyboardMoveInput() {
  47643. this._keys = new Array();
  47644. this.keysUp = [38];
  47645. this.keysDown = [40];
  47646. this.keysLeft = [37];
  47647. this.keysRight = [39];
  47648. this.keysReset = [220];
  47649. this.panningSensibility = 50.0;
  47650. this.zoomingSensibility = 25.0;
  47651. this.useAltToZoom = true;
  47652. }
  47653. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47654. var _this = this;
  47655. if (this._onCanvasBlurObserver) {
  47656. return;
  47657. }
  47658. this._scene = this.camera.getScene();
  47659. this._engine = this._scene.getEngine();
  47660. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47661. _this._keys = [];
  47662. });
  47663. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47664. var evt = info.event;
  47665. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47666. _this._ctrlPressed = evt.ctrlKey;
  47667. _this._altPressed = evt.altKey;
  47668. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47669. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47670. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47671. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47672. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47673. var index = _this._keys.indexOf(evt.keyCode);
  47674. if (index === -1) {
  47675. _this._keys.push(evt.keyCode);
  47676. }
  47677. if (evt.preventDefault) {
  47678. if (!noPreventDefault) {
  47679. evt.preventDefault();
  47680. }
  47681. }
  47682. }
  47683. }
  47684. else {
  47685. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47686. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47687. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47688. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47689. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47690. var index = _this._keys.indexOf(evt.keyCode);
  47691. if (index >= 0) {
  47692. _this._keys.splice(index, 1);
  47693. }
  47694. if (evt.preventDefault) {
  47695. if (!noPreventDefault) {
  47696. evt.preventDefault();
  47697. }
  47698. }
  47699. }
  47700. }
  47701. });
  47702. };
  47703. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47704. if (this._scene) {
  47705. if (this._onKeyboardObserver) {
  47706. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47707. }
  47708. if (this._onCanvasBlurObserver) {
  47709. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47710. }
  47711. this._onKeyboardObserver = null;
  47712. this._onCanvasBlurObserver = null;
  47713. }
  47714. this._keys = [];
  47715. };
  47716. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47717. if (this._onKeyboardObserver) {
  47718. var camera = this.camera;
  47719. for (var index = 0; index < this._keys.length; index++) {
  47720. var keyCode = this._keys[index];
  47721. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47722. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47723. camera.inertialPanningX -= 1 / this.panningSensibility;
  47724. }
  47725. else {
  47726. camera.inertialAlphaOffset -= 0.01;
  47727. }
  47728. }
  47729. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47730. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47731. camera.inertialPanningY += 1 / this.panningSensibility;
  47732. }
  47733. else if (this._altPressed && this.useAltToZoom) {
  47734. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47735. }
  47736. else {
  47737. camera.inertialBetaOffset -= 0.01;
  47738. }
  47739. }
  47740. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47741. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47742. camera.inertialPanningX += 1 / this.panningSensibility;
  47743. }
  47744. else {
  47745. camera.inertialAlphaOffset += 0.01;
  47746. }
  47747. }
  47748. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47749. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47750. camera.inertialPanningY -= 1 / this.panningSensibility;
  47751. }
  47752. else if (this._altPressed && this.useAltToZoom) {
  47753. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47754. }
  47755. else {
  47756. camera.inertialBetaOffset += 0.01;
  47757. }
  47758. }
  47759. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47760. camera.restoreState();
  47761. }
  47762. }
  47763. }
  47764. };
  47765. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47766. return "ArcRotateCameraKeyboardMoveInput";
  47767. };
  47768. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47769. return "keyboard";
  47770. };
  47771. __decorate([
  47772. BABYLON.serialize()
  47773. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47774. __decorate([
  47775. BABYLON.serialize()
  47776. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47777. __decorate([
  47778. BABYLON.serialize()
  47779. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47780. __decorate([
  47781. BABYLON.serialize()
  47782. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47783. __decorate([
  47784. BABYLON.serialize()
  47785. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47786. __decorate([
  47787. BABYLON.serialize()
  47788. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47789. __decorate([
  47790. BABYLON.serialize()
  47791. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47792. __decorate([
  47793. BABYLON.serialize()
  47794. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47795. return ArcRotateCameraKeyboardMoveInput;
  47796. }());
  47797. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47798. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47799. })(BABYLON || (BABYLON = {}));
  47800. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47801. var BABYLON;
  47802. (function (BABYLON) {
  47803. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47804. function ArcRotateCameraMouseWheelInput() {
  47805. this.wheelPrecision = 3.0;
  47806. /**
  47807. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47808. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47809. */
  47810. this.wheelDeltaPercentage = 0;
  47811. }
  47812. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47813. var _this = this;
  47814. this._wheel = function (p, s) {
  47815. //sanity check - this should be a PointerWheel event.
  47816. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47817. return;
  47818. var event = p.event;
  47819. var delta = 0;
  47820. if (event.wheelDelta) {
  47821. if (_this.wheelDeltaPercentage) {
  47822. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47823. if (event.wheelDelta > 0) {
  47824. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47825. }
  47826. else {
  47827. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47828. }
  47829. }
  47830. else {
  47831. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47832. }
  47833. }
  47834. else if (event.detail) {
  47835. delta = -event.detail / _this.wheelPrecision;
  47836. }
  47837. if (delta)
  47838. _this.camera.inertialRadiusOffset += delta;
  47839. if (event.preventDefault) {
  47840. if (!noPreventDefault) {
  47841. event.preventDefault();
  47842. }
  47843. }
  47844. };
  47845. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47846. };
  47847. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47848. if (this._observer && element) {
  47849. this.camera.getScene().onPointerObservable.remove(this._observer);
  47850. this._observer = null;
  47851. this._wheel = null;
  47852. }
  47853. };
  47854. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47855. return "ArcRotateCameraMouseWheelInput";
  47856. };
  47857. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47858. return "mousewheel";
  47859. };
  47860. __decorate([
  47861. BABYLON.serialize()
  47862. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47863. __decorate([
  47864. BABYLON.serialize()
  47865. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47866. return ArcRotateCameraMouseWheelInput;
  47867. }());
  47868. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47869. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47870. })(BABYLON || (BABYLON = {}));
  47871. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47872. var BABYLON;
  47873. (function (BABYLON) {
  47874. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47875. function ArcRotateCameraPointersInput() {
  47876. this.buttons = [0, 1, 2];
  47877. this.angularSensibilityX = 1000.0;
  47878. this.angularSensibilityY = 1000.0;
  47879. this.pinchPrecision = 12.0;
  47880. /**
  47881. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47882. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47883. */
  47884. this.pinchDeltaPercentage = 0;
  47885. this.panningSensibility = 1000.0;
  47886. this.multiTouchPanning = true;
  47887. this.multiTouchPanAndZoom = true;
  47888. this._isPanClick = false;
  47889. this.pinchInwards = true;
  47890. }
  47891. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47892. var _this = this;
  47893. var engine = this.camera.getEngine();
  47894. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47895. var pointA = null;
  47896. var pointB = null;
  47897. var previousPinchSquaredDistance = 0;
  47898. var initialDistance = 0;
  47899. var twoFingerActivityCount = 0;
  47900. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47901. this._pointerInput = function (p, s) {
  47902. var evt = p.event;
  47903. var isTouch = p.event.pointerType === "touch";
  47904. if (engine.isInVRExclusivePointerMode) {
  47905. return;
  47906. }
  47907. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47908. return;
  47909. }
  47910. var srcElement = (evt.srcElement || evt.target);
  47911. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47912. try {
  47913. srcElement.setPointerCapture(evt.pointerId);
  47914. }
  47915. catch (e) {
  47916. //Nothing to do with the error. Execution will continue.
  47917. }
  47918. // Manage panning with pan button click
  47919. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47920. // manage pointers
  47921. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47922. if (pointA === null) {
  47923. pointA = cacheSoloPointer;
  47924. }
  47925. else if (pointB === null) {
  47926. pointB = cacheSoloPointer;
  47927. }
  47928. if (!noPreventDefault) {
  47929. evt.preventDefault();
  47930. element.focus();
  47931. }
  47932. }
  47933. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47934. _this.camera.restoreState();
  47935. }
  47936. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47937. try {
  47938. srcElement.releasePointerCapture(evt.pointerId);
  47939. }
  47940. catch (e) {
  47941. //Nothing to do with the error.
  47942. }
  47943. cacheSoloPointer = null;
  47944. previousPinchSquaredDistance = 0;
  47945. previousMultiTouchPanPosition.isPaning = false;
  47946. previousMultiTouchPanPosition.isPinching = false;
  47947. twoFingerActivityCount = 0;
  47948. initialDistance = 0;
  47949. if (!isTouch) {
  47950. pointB = null; // Mouse and pen are mono pointer
  47951. }
  47952. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47953. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47954. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47955. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47956. if (engine._badOS) {
  47957. pointA = pointB = null;
  47958. }
  47959. else {
  47960. //only remove the impacted pointer in case of multitouch allowing on most
  47961. //platforms switching from rotate to zoom and pan seamlessly.
  47962. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47963. pointA = pointB;
  47964. pointB = null;
  47965. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47966. }
  47967. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47968. pointB = null;
  47969. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47970. }
  47971. else {
  47972. pointA = pointB = null;
  47973. }
  47974. }
  47975. if (!noPreventDefault) {
  47976. evt.preventDefault();
  47977. }
  47978. }
  47979. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47980. if (!noPreventDefault) {
  47981. evt.preventDefault();
  47982. }
  47983. // One button down
  47984. if (pointA && pointB === null && cacheSoloPointer) {
  47985. if (_this.panningSensibility !== 0 &&
  47986. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47987. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47988. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47989. }
  47990. else {
  47991. var offsetX = evt.clientX - cacheSoloPointer.x;
  47992. var offsetY = evt.clientY - cacheSoloPointer.y;
  47993. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47994. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47995. }
  47996. cacheSoloPointer.x = evt.clientX;
  47997. cacheSoloPointer.y = evt.clientY;
  47998. }
  47999. // Two buttons down: pinch/pan
  48000. else if (pointA && pointB) {
  48001. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48002. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48003. ed.x = evt.clientX;
  48004. ed.y = evt.clientY;
  48005. var direction = _this.pinchInwards ? 1 : -1;
  48006. var distX = pointA.x - pointB.x;
  48007. var distY = pointA.y - pointB.y;
  48008. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48009. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48010. if (previousPinchSquaredDistance === 0) {
  48011. initialDistance = pinchDistance;
  48012. previousPinchSquaredDistance = pinchSquaredDistance;
  48013. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48014. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48015. return;
  48016. }
  48017. if (_this.multiTouchPanAndZoom) {
  48018. if (_this.pinchDeltaPercentage) {
  48019. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48020. }
  48021. else {
  48022. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48023. (_this.pinchPrecision *
  48024. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48025. direction);
  48026. }
  48027. if (_this.panningSensibility !== 0) {
  48028. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48029. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48030. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48031. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48032. previousMultiTouchPanPosition.x = pointersCenterX;
  48033. previousMultiTouchPanPosition.y = pointersCenterY;
  48034. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48035. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48036. }
  48037. }
  48038. else {
  48039. twoFingerActivityCount++;
  48040. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48041. if (_this.pinchDeltaPercentage) {
  48042. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48043. }
  48044. else {
  48045. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48046. (_this.pinchPrecision *
  48047. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48048. direction);
  48049. }
  48050. previousMultiTouchPanPosition.isPaning = false;
  48051. previousMultiTouchPanPosition.isPinching = true;
  48052. }
  48053. else {
  48054. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48055. if (!previousMultiTouchPanPosition.isPaning) {
  48056. previousMultiTouchPanPosition.isPaning = true;
  48057. previousMultiTouchPanPosition.isPinching = false;
  48058. previousMultiTouchPanPosition.x = ed.x;
  48059. previousMultiTouchPanPosition.y = ed.y;
  48060. return;
  48061. }
  48062. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48063. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48064. }
  48065. }
  48066. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48067. previousMultiTouchPanPosition.x = ed.x;
  48068. previousMultiTouchPanPosition.y = ed.y;
  48069. }
  48070. }
  48071. previousPinchSquaredDistance = pinchSquaredDistance;
  48072. }
  48073. }
  48074. };
  48075. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48076. this._onContextMenu = function (evt) {
  48077. evt.preventDefault();
  48078. };
  48079. if (!this.camera._useCtrlForPanning) {
  48080. element.addEventListener("contextmenu", this._onContextMenu, false);
  48081. }
  48082. this._onLostFocus = function () {
  48083. //this._keys = [];
  48084. pointA = pointB = null;
  48085. previousPinchSquaredDistance = 0;
  48086. previousMultiTouchPanPosition.isPaning = false;
  48087. previousMultiTouchPanPosition.isPinching = false;
  48088. twoFingerActivityCount = 0;
  48089. cacheSoloPointer = null;
  48090. initialDistance = 0;
  48091. };
  48092. this._onMouseMove = function (evt) {
  48093. if (!engine.isPointerLock) {
  48094. return;
  48095. }
  48096. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48097. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48098. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48099. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48100. if (!noPreventDefault) {
  48101. evt.preventDefault();
  48102. }
  48103. };
  48104. this._onGestureStart = function (e) {
  48105. if (window.MSGesture === undefined) {
  48106. return;
  48107. }
  48108. if (!_this._MSGestureHandler) {
  48109. _this._MSGestureHandler = new MSGesture();
  48110. _this._MSGestureHandler.target = element;
  48111. }
  48112. _this._MSGestureHandler.addPointer(e.pointerId);
  48113. };
  48114. this._onGesture = function (e) {
  48115. _this.camera.radius *= e.scale;
  48116. if (e.preventDefault) {
  48117. if (!noPreventDefault) {
  48118. e.stopPropagation();
  48119. e.preventDefault();
  48120. }
  48121. }
  48122. };
  48123. element.addEventListener("mousemove", this._onMouseMove, false);
  48124. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48125. element.addEventListener("MSGestureChange", this._onGesture, false);
  48126. BABYLON.Tools.RegisterTopRootEvents([
  48127. { name: "blur", handler: this._onLostFocus }
  48128. ]);
  48129. };
  48130. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48131. if (this._onLostFocus) {
  48132. BABYLON.Tools.UnregisterTopRootEvents([
  48133. { name: "blur", handler: this._onLostFocus }
  48134. ]);
  48135. }
  48136. if (element && this._observer) {
  48137. this.camera.getScene().onPointerObservable.remove(this._observer);
  48138. this._observer = null;
  48139. if (this._onContextMenu) {
  48140. element.removeEventListener("contextmenu", this._onContextMenu);
  48141. }
  48142. if (this._onMouseMove) {
  48143. element.removeEventListener("mousemove", this._onMouseMove);
  48144. }
  48145. if (this._onGestureStart) {
  48146. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48147. }
  48148. if (this._onGesture) {
  48149. element.removeEventListener("MSGestureChange", this._onGesture);
  48150. }
  48151. this._isPanClick = false;
  48152. this.pinchInwards = true;
  48153. this._onMouseMove = null;
  48154. this._onGestureStart = null;
  48155. this._onGesture = null;
  48156. this._MSGestureHandler = null;
  48157. this._onLostFocus = null;
  48158. this._onContextMenu = null;
  48159. }
  48160. };
  48161. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48162. return "ArcRotateCameraPointersInput";
  48163. };
  48164. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48165. return "pointers";
  48166. };
  48167. __decorate([
  48168. BABYLON.serialize()
  48169. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48170. __decorate([
  48171. BABYLON.serialize()
  48172. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48173. __decorate([
  48174. BABYLON.serialize()
  48175. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48176. __decorate([
  48177. BABYLON.serialize()
  48178. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48179. __decorate([
  48180. BABYLON.serialize()
  48181. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48182. __decorate([
  48183. BABYLON.serialize()
  48184. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48185. __decorate([
  48186. BABYLON.serialize()
  48187. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48188. __decorate([
  48189. BABYLON.serialize()
  48190. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48191. return ArcRotateCameraPointersInput;
  48192. }());
  48193. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48194. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48195. })(BABYLON || (BABYLON = {}));
  48196. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48197. var BABYLON;
  48198. (function (BABYLON) {
  48199. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48200. __extends(ArcRotateCameraInputsManager, _super);
  48201. function ArcRotateCameraInputsManager(camera) {
  48202. return _super.call(this, camera) || this;
  48203. }
  48204. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48205. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48206. return this;
  48207. };
  48208. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48209. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48210. return this;
  48211. };
  48212. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48213. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48214. return this;
  48215. };
  48216. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48217. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48218. return this;
  48219. };
  48220. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48221. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48222. return this;
  48223. };
  48224. return ArcRotateCameraInputsManager;
  48225. }(BABYLON.CameraInputsManager));
  48226. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48227. })(BABYLON || (BABYLON = {}));
  48228. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48229. var BABYLON;
  48230. (function (BABYLON) {
  48231. var ArcRotateCamera = /** @class */ (function (_super) {
  48232. __extends(ArcRotateCamera, _super);
  48233. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48234. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48235. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48236. _this.inertialAlphaOffset = 0;
  48237. _this.inertialBetaOffset = 0;
  48238. _this.inertialRadiusOffset = 0;
  48239. _this.lowerAlphaLimit = null;
  48240. _this.upperAlphaLimit = null;
  48241. _this.lowerBetaLimit = 0.01;
  48242. _this.upperBetaLimit = Math.PI;
  48243. _this.lowerRadiusLimit = null;
  48244. _this.upperRadiusLimit = null;
  48245. _this.inertialPanningX = 0;
  48246. _this.inertialPanningY = 0;
  48247. _this.pinchToPanMaxDistance = 20;
  48248. _this.panningDistanceLimit = null;
  48249. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48250. _this.panningInertia = 0.9;
  48251. //-- end properties for backward compatibility for inputs
  48252. _this.zoomOnFactor = 1;
  48253. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48254. _this.allowUpsideDown = true;
  48255. _this._viewMatrix = new BABYLON.Matrix();
  48256. // Panning
  48257. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48258. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48259. _this.checkCollisions = false;
  48260. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48261. _this._previousPosition = BABYLON.Vector3.Zero();
  48262. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48263. _this._newPosition = BABYLON.Vector3.Zero();
  48264. _this._computationVector = BABYLON.Vector3.Zero();
  48265. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48266. if (collidedMesh === void 0) { collidedMesh = null; }
  48267. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48268. newPosition.multiplyInPlace(_this._collider._radius);
  48269. }
  48270. if (!collidedMesh) {
  48271. _this._previousPosition.copyFrom(_this.position);
  48272. }
  48273. else {
  48274. _this.setPosition(newPosition);
  48275. if (_this.onCollide) {
  48276. _this.onCollide(collidedMesh);
  48277. }
  48278. }
  48279. // Recompute because of constraints
  48280. var cosa = Math.cos(_this.alpha);
  48281. var sina = Math.sin(_this.alpha);
  48282. var cosb = Math.cos(_this.beta);
  48283. var sinb = Math.sin(_this.beta);
  48284. if (sinb === 0) {
  48285. sinb = 0.0001;
  48286. }
  48287. var target = _this._getTargetPosition();
  48288. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48289. target.addToRef(_this._computationVector, _this._newPosition);
  48290. _this.position.copyFrom(_this._newPosition);
  48291. var up = _this.upVector;
  48292. if (_this.allowUpsideDown && _this.beta < 0) {
  48293. up = up.clone();
  48294. up = up.negate();
  48295. }
  48296. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48297. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48298. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48299. _this._collisionTriggered = false;
  48300. };
  48301. _this._target = BABYLON.Vector3.Zero();
  48302. if (target) {
  48303. _this.setTarget(target);
  48304. }
  48305. _this.alpha = alpha;
  48306. _this.beta = beta;
  48307. _this.radius = radius;
  48308. _this.getViewMatrix();
  48309. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48310. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48311. return _this;
  48312. }
  48313. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48314. get: function () {
  48315. return this._target;
  48316. },
  48317. set: function (value) {
  48318. this.setTarget(value);
  48319. },
  48320. enumerable: true,
  48321. configurable: true
  48322. });
  48323. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48324. //-- begin properties for backward compatibility for inputs
  48325. get: function () {
  48326. var pointers = this.inputs.attached["pointers"];
  48327. if (pointers)
  48328. return pointers.angularSensibilityX;
  48329. return 0;
  48330. },
  48331. set: function (value) {
  48332. var pointers = this.inputs.attached["pointers"];
  48333. if (pointers) {
  48334. pointers.angularSensibilityX = value;
  48335. }
  48336. },
  48337. enumerable: true,
  48338. configurable: true
  48339. });
  48340. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48341. get: function () {
  48342. var pointers = this.inputs.attached["pointers"];
  48343. if (pointers)
  48344. return pointers.angularSensibilityY;
  48345. return 0;
  48346. },
  48347. set: function (value) {
  48348. var pointers = this.inputs.attached["pointers"];
  48349. if (pointers) {
  48350. pointers.angularSensibilityY = value;
  48351. }
  48352. },
  48353. enumerable: true,
  48354. configurable: true
  48355. });
  48356. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48357. get: function () {
  48358. var pointers = this.inputs.attached["pointers"];
  48359. if (pointers)
  48360. return pointers.pinchPrecision;
  48361. return 0;
  48362. },
  48363. set: function (value) {
  48364. var pointers = this.inputs.attached["pointers"];
  48365. if (pointers) {
  48366. pointers.pinchPrecision = value;
  48367. }
  48368. },
  48369. enumerable: true,
  48370. configurable: true
  48371. });
  48372. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48373. get: function () {
  48374. var pointers = this.inputs.attached["pointers"];
  48375. if (pointers)
  48376. return pointers.pinchDeltaPercentage;
  48377. return 0;
  48378. },
  48379. set: function (value) {
  48380. var pointers = this.inputs.attached["pointers"];
  48381. if (pointers) {
  48382. pointers.pinchDeltaPercentage = value;
  48383. }
  48384. },
  48385. enumerable: true,
  48386. configurable: true
  48387. });
  48388. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48389. get: function () {
  48390. var pointers = this.inputs.attached["pointers"];
  48391. if (pointers)
  48392. return pointers.panningSensibility;
  48393. return 0;
  48394. },
  48395. set: function (value) {
  48396. var pointers = this.inputs.attached["pointers"];
  48397. if (pointers) {
  48398. pointers.panningSensibility = value;
  48399. }
  48400. },
  48401. enumerable: true,
  48402. configurable: true
  48403. });
  48404. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48405. get: function () {
  48406. var keyboard = this.inputs.attached["keyboard"];
  48407. if (keyboard)
  48408. return keyboard.keysUp;
  48409. return [];
  48410. },
  48411. set: function (value) {
  48412. var keyboard = this.inputs.attached["keyboard"];
  48413. if (keyboard)
  48414. keyboard.keysUp = value;
  48415. },
  48416. enumerable: true,
  48417. configurable: true
  48418. });
  48419. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48420. get: function () {
  48421. var keyboard = this.inputs.attached["keyboard"];
  48422. if (keyboard)
  48423. return keyboard.keysDown;
  48424. return [];
  48425. },
  48426. set: function (value) {
  48427. var keyboard = this.inputs.attached["keyboard"];
  48428. if (keyboard)
  48429. keyboard.keysDown = value;
  48430. },
  48431. enumerable: true,
  48432. configurable: true
  48433. });
  48434. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48435. get: function () {
  48436. var keyboard = this.inputs.attached["keyboard"];
  48437. if (keyboard)
  48438. return keyboard.keysLeft;
  48439. return [];
  48440. },
  48441. set: function (value) {
  48442. var keyboard = this.inputs.attached["keyboard"];
  48443. if (keyboard)
  48444. keyboard.keysLeft = value;
  48445. },
  48446. enumerable: true,
  48447. configurable: true
  48448. });
  48449. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48450. get: function () {
  48451. var keyboard = this.inputs.attached["keyboard"];
  48452. if (keyboard)
  48453. return keyboard.keysRight;
  48454. return [];
  48455. },
  48456. set: function (value) {
  48457. var keyboard = this.inputs.attached["keyboard"];
  48458. if (keyboard)
  48459. keyboard.keysRight = value;
  48460. },
  48461. enumerable: true,
  48462. configurable: true
  48463. });
  48464. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48465. get: function () {
  48466. var mousewheel = this.inputs.attached["mousewheel"];
  48467. if (mousewheel)
  48468. return mousewheel.wheelPrecision;
  48469. return 0;
  48470. },
  48471. set: function (value) {
  48472. var mousewheel = this.inputs.attached["mousewheel"];
  48473. if (mousewheel)
  48474. mousewheel.wheelPrecision = value;
  48475. },
  48476. enumerable: true,
  48477. configurable: true
  48478. });
  48479. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48480. get: function () {
  48481. var mousewheel = this.inputs.attached["mousewheel"];
  48482. if (mousewheel)
  48483. return mousewheel.wheelDeltaPercentage;
  48484. return 0;
  48485. },
  48486. set: function (value) {
  48487. var mousewheel = this.inputs.attached["mousewheel"];
  48488. if (mousewheel)
  48489. mousewheel.wheelDeltaPercentage = value;
  48490. },
  48491. enumerable: true,
  48492. configurable: true
  48493. });
  48494. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48495. get: function () {
  48496. return this._bouncingBehavior;
  48497. },
  48498. enumerable: true,
  48499. configurable: true
  48500. });
  48501. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48502. get: function () {
  48503. return this._bouncingBehavior != null;
  48504. },
  48505. set: function (value) {
  48506. if (value === this.useBouncingBehavior) {
  48507. return;
  48508. }
  48509. if (value) {
  48510. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48511. this.addBehavior(this._bouncingBehavior);
  48512. }
  48513. else if (this._bouncingBehavior) {
  48514. this.removeBehavior(this._bouncingBehavior);
  48515. this._bouncingBehavior = null;
  48516. }
  48517. },
  48518. enumerable: true,
  48519. configurable: true
  48520. });
  48521. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48522. get: function () {
  48523. return this._framingBehavior;
  48524. },
  48525. enumerable: true,
  48526. configurable: true
  48527. });
  48528. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48529. get: function () {
  48530. return this._framingBehavior != null;
  48531. },
  48532. set: function (value) {
  48533. if (value === this.useFramingBehavior) {
  48534. return;
  48535. }
  48536. if (value) {
  48537. this._framingBehavior = new BABYLON.FramingBehavior();
  48538. this.addBehavior(this._framingBehavior);
  48539. }
  48540. else if (this._framingBehavior) {
  48541. this.removeBehavior(this._framingBehavior);
  48542. this._framingBehavior = null;
  48543. }
  48544. },
  48545. enumerable: true,
  48546. configurable: true
  48547. });
  48548. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48549. get: function () {
  48550. return this._autoRotationBehavior;
  48551. },
  48552. enumerable: true,
  48553. configurable: true
  48554. });
  48555. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48556. get: function () {
  48557. return this._autoRotationBehavior != null;
  48558. },
  48559. set: function (value) {
  48560. if (value === this.useAutoRotationBehavior) {
  48561. return;
  48562. }
  48563. if (value) {
  48564. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48565. this.addBehavior(this._autoRotationBehavior);
  48566. }
  48567. else if (this._autoRotationBehavior) {
  48568. this.removeBehavior(this._autoRotationBehavior);
  48569. this._autoRotationBehavior = null;
  48570. }
  48571. },
  48572. enumerable: true,
  48573. configurable: true
  48574. });
  48575. // Cache
  48576. ArcRotateCamera.prototype._initCache = function () {
  48577. _super.prototype._initCache.call(this);
  48578. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48579. this._cache.alpha = undefined;
  48580. this._cache.beta = undefined;
  48581. this._cache.radius = undefined;
  48582. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48583. };
  48584. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48585. if (!ignoreParentClass) {
  48586. _super.prototype._updateCache.call(this);
  48587. }
  48588. this._cache._target.copyFrom(this._getTargetPosition());
  48589. this._cache.alpha = this.alpha;
  48590. this._cache.beta = this.beta;
  48591. this._cache.radius = this.radius;
  48592. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48593. };
  48594. ArcRotateCamera.prototype._getTargetPosition = function () {
  48595. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48596. var pos = this._targetHost.getAbsolutePosition();
  48597. if (this._targetBoundingCenter) {
  48598. pos.addToRef(this._targetBoundingCenter, this._target);
  48599. }
  48600. else {
  48601. this._target.copyFrom(pos);
  48602. }
  48603. }
  48604. var lockedTargetPosition = this._getLockedTargetPosition();
  48605. if (lockedTargetPosition) {
  48606. return lockedTargetPosition;
  48607. }
  48608. return this._target;
  48609. };
  48610. ArcRotateCamera.prototype.storeState = function () {
  48611. this._storedAlpha = this.alpha;
  48612. this._storedBeta = this.beta;
  48613. this._storedRadius = this.radius;
  48614. this._storedTarget = this._getTargetPosition().clone();
  48615. return _super.prototype.storeState.call(this);
  48616. };
  48617. /**
  48618. * Restored camera state. You must call storeState() first
  48619. */
  48620. ArcRotateCamera.prototype._restoreStateValues = function () {
  48621. if (!_super.prototype._restoreStateValues.call(this)) {
  48622. return false;
  48623. }
  48624. this.alpha = this._storedAlpha;
  48625. this.beta = this._storedBeta;
  48626. this.radius = this._storedRadius;
  48627. this.setTarget(this._storedTarget.clone());
  48628. this.inertialAlphaOffset = 0;
  48629. this.inertialBetaOffset = 0;
  48630. this.inertialRadiusOffset = 0;
  48631. this.inertialPanningX = 0;
  48632. this.inertialPanningY = 0;
  48633. return true;
  48634. };
  48635. // Synchronized
  48636. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48637. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48638. return false;
  48639. return this._cache._target.equals(this._getTargetPosition())
  48640. && this._cache.alpha === this.alpha
  48641. && this._cache.beta === this.beta
  48642. && this._cache.radius === this.radius
  48643. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48644. };
  48645. // Methods
  48646. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48647. var _this = this;
  48648. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48649. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48650. this._useCtrlForPanning = useCtrlForPanning;
  48651. this._panningMouseButton = panningMouseButton;
  48652. this.inputs.attachElement(element, noPreventDefault);
  48653. this._reset = function () {
  48654. _this.inertialAlphaOffset = 0;
  48655. _this.inertialBetaOffset = 0;
  48656. _this.inertialRadiusOffset = 0;
  48657. _this.inertialPanningX = 0;
  48658. _this.inertialPanningY = 0;
  48659. };
  48660. };
  48661. ArcRotateCamera.prototype.detachControl = function (element) {
  48662. this.inputs.detachElement(element);
  48663. if (this._reset) {
  48664. this._reset();
  48665. }
  48666. };
  48667. ArcRotateCamera.prototype._checkInputs = function () {
  48668. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48669. if (this._collisionTriggered) {
  48670. return;
  48671. }
  48672. this.inputs.checkInputs();
  48673. // Inertia
  48674. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48675. var inertialAlphaOffset = this.inertialAlphaOffset;
  48676. if (this.beta <= 0)
  48677. inertialAlphaOffset *= -1;
  48678. if (this.getScene().useRightHandedSystem)
  48679. inertialAlphaOffset *= -1;
  48680. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48681. inertialAlphaOffset *= -1;
  48682. this.alpha += inertialAlphaOffset;
  48683. this.beta += this.inertialBetaOffset;
  48684. this.radius -= this.inertialRadiusOffset;
  48685. this.inertialAlphaOffset *= this.inertia;
  48686. this.inertialBetaOffset *= this.inertia;
  48687. this.inertialRadiusOffset *= this.inertia;
  48688. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48689. this.inertialAlphaOffset = 0;
  48690. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48691. this.inertialBetaOffset = 0;
  48692. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48693. this.inertialRadiusOffset = 0;
  48694. }
  48695. // Panning inertia
  48696. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48697. if (!this._localDirection) {
  48698. this._localDirection = BABYLON.Vector3.Zero();
  48699. this._transformedDirection = BABYLON.Vector3.Zero();
  48700. }
  48701. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48702. this._localDirection.multiplyInPlace(this.panningAxis);
  48703. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48704. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48705. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48706. if (!this.panningAxis.y) {
  48707. this._transformedDirection.y = 0;
  48708. }
  48709. if (!this._targetHost) {
  48710. if (this.panningDistanceLimit) {
  48711. this._transformedDirection.addInPlace(this._target);
  48712. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48713. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48714. this._target.copyFrom(this._transformedDirection);
  48715. }
  48716. }
  48717. else {
  48718. this._target.addInPlace(this._transformedDirection);
  48719. }
  48720. }
  48721. this.inertialPanningX *= this.panningInertia;
  48722. this.inertialPanningY *= this.panningInertia;
  48723. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48724. this.inertialPanningX = 0;
  48725. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48726. this.inertialPanningY = 0;
  48727. }
  48728. // Limits
  48729. this._checkLimits();
  48730. _super.prototype._checkInputs.call(this);
  48731. };
  48732. ArcRotateCamera.prototype._checkLimits = function () {
  48733. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48734. if (this.allowUpsideDown && this.beta > Math.PI) {
  48735. this.beta = this.beta - (2 * Math.PI);
  48736. }
  48737. }
  48738. else {
  48739. if (this.beta < this.lowerBetaLimit) {
  48740. this.beta = this.lowerBetaLimit;
  48741. }
  48742. }
  48743. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48744. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48745. this.beta = this.beta + (2 * Math.PI);
  48746. }
  48747. }
  48748. else {
  48749. if (this.beta > this.upperBetaLimit) {
  48750. this.beta = this.upperBetaLimit;
  48751. }
  48752. }
  48753. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48754. this.alpha = this.lowerAlphaLimit;
  48755. }
  48756. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48757. this.alpha = this.upperAlphaLimit;
  48758. }
  48759. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48760. this.radius = this.lowerRadiusLimit;
  48761. }
  48762. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48763. this.radius = this.upperRadiusLimit;
  48764. }
  48765. };
  48766. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48767. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48768. this.radius = this._computationVector.length();
  48769. if (this.radius === 0) {
  48770. this.radius = 0.0001; // Just to avoid division by zero
  48771. }
  48772. // Alpha
  48773. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48774. if (this._computationVector.z < 0) {
  48775. this.alpha = 2 * Math.PI - this.alpha;
  48776. }
  48777. // Beta
  48778. this.beta = Math.acos(this._computationVector.y / this.radius);
  48779. this._checkLimits();
  48780. };
  48781. ArcRotateCamera.prototype.setPosition = function (position) {
  48782. if (this.position.equals(position)) {
  48783. return;
  48784. }
  48785. this.position.copyFrom(position);
  48786. this.rebuildAnglesAndRadius();
  48787. };
  48788. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48789. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48790. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48791. if (target.getBoundingInfo) {
  48792. if (toBoundingCenter) {
  48793. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48794. }
  48795. else {
  48796. this._targetBoundingCenter = null;
  48797. }
  48798. this._targetHost = target;
  48799. this._target = this._getTargetPosition();
  48800. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48801. }
  48802. else {
  48803. var newTarget = target;
  48804. var currentTarget = this._getTargetPosition();
  48805. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48806. return;
  48807. }
  48808. this._targetHost = null;
  48809. this._target = newTarget;
  48810. this._targetBoundingCenter = null;
  48811. this.onMeshTargetChangedObservable.notifyObservers(null);
  48812. }
  48813. this.rebuildAnglesAndRadius();
  48814. };
  48815. ArcRotateCamera.prototype._getViewMatrix = function () {
  48816. // Compute
  48817. var cosa = Math.cos(this.alpha);
  48818. var sina = Math.sin(this.alpha);
  48819. var cosb = Math.cos(this.beta);
  48820. var sinb = Math.sin(this.beta);
  48821. if (sinb === 0) {
  48822. sinb = 0.0001;
  48823. }
  48824. var target = this._getTargetPosition();
  48825. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48826. target.addToRef(this._computationVector, this._newPosition);
  48827. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48828. if (!this._collider) {
  48829. this._collider = new BABYLON.Collider();
  48830. }
  48831. this._collider._radius = this.collisionRadius;
  48832. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48833. this._collisionTriggered = true;
  48834. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48835. }
  48836. else {
  48837. this.position.copyFrom(this._newPosition);
  48838. var up = this.upVector;
  48839. if (this.allowUpsideDown && sinb < 0) {
  48840. up = up.clone();
  48841. up = up.negate();
  48842. }
  48843. this._computeViewMatrix(this.position, target, up);
  48844. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48845. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48846. }
  48847. this._currentTarget = target;
  48848. return this._viewMatrix;
  48849. };
  48850. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48851. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48852. meshes = meshes || this.getScene().meshes;
  48853. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48854. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48855. this.radius = distance * this.zoomOnFactor;
  48856. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48857. };
  48858. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48859. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48860. var meshesOrMinMaxVector;
  48861. var distance;
  48862. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48863. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48864. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48865. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48866. }
  48867. else { //minMaxVector and distance
  48868. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48869. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48870. distance = minMaxVectorAndDistance.distance;
  48871. }
  48872. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48873. if (!doNotUpdateMaxZ) {
  48874. this.maxZ = distance * 2;
  48875. }
  48876. };
  48877. /**
  48878. * @override
  48879. * Override Camera.createRigCamera
  48880. */
  48881. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48882. var alphaShift = 0;
  48883. switch (this.cameraRigMode) {
  48884. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48885. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48886. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48887. case BABYLON.Camera.RIG_MODE_VR:
  48888. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48889. break;
  48890. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48891. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48892. break;
  48893. }
  48894. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48895. rigCam._cameraRigParams = {};
  48896. return rigCam;
  48897. };
  48898. /**
  48899. * @override
  48900. * Override Camera._updateRigCameras
  48901. */
  48902. ArcRotateCamera.prototype._updateRigCameras = function () {
  48903. var camLeft = this._rigCameras[0];
  48904. var camRight = this._rigCameras[1];
  48905. camLeft.beta = camRight.beta = this.beta;
  48906. camLeft.radius = camRight.radius = this.radius;
  48907. switch (this.cameraRigMode) {
  48908. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48909. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48910. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48911. case BABYLON.Camera.RIG_MODE_VR:
  48912. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48913. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48914. break;
  48915. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48916. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48917. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48918. break;
  48919. }
  48920. _super.prototype._updateRigCameras.call(this);
  48921. };
  48922. ArcRotateCamera.prototype.dispose = function () {
  48923. this.inputs.clear();
  48924. _super.prototype.dispose.call(this);
  48925. };
  48926. ArcRotateCamera.prototype.getClassName = function () {
  48927. return "ArcRotateCamera";
  48928. };
  48929. __decorate([
  48930. BABYLON.serialize()
  48931. ], ArcRotateCamera.prototype, "alpha", void 0);
  48932. __decorate([
  48933. BABYLON.serialize()
  48934. ], ArcRotateCamera.prototype, "beta", void 0);
  48935. __decorate([
  48936. BABYLON.serialize()
  48937. ], ArcRotateCamera.prototype, "radius", void 0);
  48938. __decorate([
  48939. BABYLON.serializeAsVector3("target")
  48940. ], ArcRotateCamera.prototype, "_target", void 0);
  48941. __decorate([
  48942. BABYLON.serialize()
  48943. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48944. __decorate([
  48945. BABYLON.serialize()
  48946. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48947. __decorate([
  48948. BABYLON.serialize()
  48949. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48950. __decorate([
  48951. BABYLON.serialize()
  48952. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48953. __decorate([
  48954. BABYLON.serialize()
  48955. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48956. __decorate([
  48957. BABYLON.serialize()
  48958. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48959. __decorate([
  48960. BABYLON.serialize()
  48961. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48962. __decorate([
  48963. BABYLON.serialize()
  48964. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48965. __decorate([
  48966. BABYLON.serialize()
  48967. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48968. __decorate([
  48969. BABYLON.serialize()
  48970. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48971. __decorate([
  48972. BABYLON.serialize()
  48973. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48974. __decorate([
  48975. BABYLON.serialize()
  48976. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48977. __decorate([
  48978. BABYLON.serialize()
  48979. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48980. __decorate([
  48981. BABYLON.serializeAsVector3()
  48982. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48983. __decorate([
  48984. BABYLON.serialize()
  48985. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48986. __decorate([
  48987. BABYLON.serialize()
  48988. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48989. __decorate([
  48990. BABYLON.serialize()
  48991. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48992. return ArcRotateCamera;
  48993. }(BABYLON.TargetCamera));
  48994. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48995. })(BABYLON || (BABYLON = {}));
  48996. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48997. var BABYLON;
  48998. (function (BABYLON) {
  48999. /**
  49000. * The HemisphericLight simulates the ambient environment light,
  49001. * so the passed direction is the light reflection direction, not the incoming direction.
  49002. */
  49003. var HemisphericLight = /** @class */ (function (_super) {
  49004. __extends(HemisphericLight, _super);
  49005. /**
  49006. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49007. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49008. * The HemisphericLight can't cast shadows.
  49009. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49010. * @param name The friendly name of the light
  49011. * @param direction The direction of the light reflection
  49012. * @param scene The scene the light belongs to
  49013. */
  49014. function HemisphericLight(name, direction, scene) {
  49015. var _this = _super.call(this, name, scene) || this;
  49016. /**
  49017. * The groundColor is the light in the opposite direction to the one specified during creation.
  49018. * 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.
  49019. */
  49020. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49021. _this.direction = direction || BABYLON.Vector3.Up();
  49022. return _this;
  49023. }
  49024. HemisphericLight.prototype._buildUniformLayout = function () {
  49025. this._uniformBuffer.addUniform("vLightData", 4);
  49026. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49027. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49028. this._uniformBuffer.addUniform("vLightGround", 3);
  49029. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49030. this._uniformBuffer.addUniform("depthValues", 2);
  49031. this._uniformBuffer.create();
  49032. };
  49033. /**
  49034. * Returns the string "HemisphericLight".
  49035. * @return The class name
  49036. */
  49037. HemisphericLight.prototype.getClassName = function () {
  49038. return "HemisphericLight";
  49039. };
  49040. /**
  49041. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49042. * Returns the updated direction.
  49043. * @param target The target the direction should point to
  49044. * @return The computed direction
  49045. */
  49046. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49047. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49048. return this.direction;
  49049. };
  49050. /**
  49051. * Returns the shadow generator associated to the light.
  49052. * @returns Always null for hemispheric lights because it does not support shadows.
  49053. */
  49054. HemisphericLight.prototype.getShadowGenerator = function () {
  49055. return null;
  49056. };
  49057. /**
  49058. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49059. * @param effect The effect to update
  49060. * @param lightIndex The index of the light in the effect to update
  49061. * @returns The hemispheric light
  49062. */
  49063. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49064. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49065. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49066. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49067. return this;
  49068. };
  49069. /**
  49070. * @hidden internal use only.
  49071. */
  49072. HemisphericLight.prototype._getWorldMatrix = function () {
  49073. if (!this._worldMatrix) {
  49074. this._worldMatrix = BABYLON.Matrix.Identity();
  49075. }
  49076. return this._worldMatrix;
  49077. };
  49078. /**
  49079. * Returns the integer 3.
  49080. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49081. */
  49082. HemisphericLight.prototype.getTypeID = function () {
  49083. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49084. };
  49085. __decorate([
  49086. BABYLON.serializeAsColor3()
  49087. ], HemisphericLight.prototype, "groundColor", void 0);
  49088. __decorate([
  49089. BABYLON.serializeAsVector3()
  49090. ], HemisphericLight.prototype, "direction", void 0);
  49091. return HemisphericLight;
  49092. }(BABYLON.Light));
  49093. BABYLON.HemisphericLight = HemisphericLight;
  49094. })(BABYLON || (BABYLON = {}));
  49095. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49096. var BABYLON;
  49097. (function (BABYLON) {
  49098. /**
  49099. * Base implementation IShadowLight
  49100. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49101. */
  49102. var ShadowLight = /** @class */ (function (_super) {
  49103. __extends(ShadowLight, _super);
  49104. function ShadowLight() {
  49105. var _this = _super !== null && _super.apply(this, arguments) || this;
  49106. _this._needProjectionMatrixCompute = true;
  49107. return _this;
  49108. }
  49109. ShadowLight.prototype._setPosition = function (value) {
  49110. this._position = value;
  49111. };
  49112. Object.defineProperty(ShadowLight.prototype, "position", {
  49113. /**
  49114. * Sets the position the shadow will be casted from. Also use as the light position for both
  49115. * point and spot lights.
  49116. */
  49117. get: function () {
  49118. return this._position;
  49119. },
  49120. /**
  49121. * Sets the position the shadow will be casted from. Also use as the light position for both
  49122. * point and spot lights.
  49123. */
  49124. set: function (value) {
  49125. this._setPosition(value);
  49126. },
  49127. enumerable: true,
  49128. configurable: true
  49129. });
  49130. ShadowLight.prototype._setDirection = function (value) {
  49131. this._direction = value;
  49132. };
  49133. Object.defineProperty(ShadowLight.prototype, "direction", {
  49134. /**
  49135. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49136. * Also use as the light direction on spot and directional lights.
  49137. */
  49138. get: function () {
  49139. return this._direction;
  49140. },
  49141. /**
  49142. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49143. * Also use as the light direction on spot and directional lights.
  49144. */
  49145. set: function (value) {
  49146. this._setDirection(value);
  49147. },
  49148. enumerable: true,
  49149. configurable: true
  49150. });
  49151. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49152. /**
  49153. * Gets the shadow projection clipping minimum z value.
  49154. */
  49155. get: function () {
  49156. return this._shadowMinZ;
  49157. },
  49158. /**
  49159. * Sets the shadow projection clipping minimum z value.
  49160. */
  49161. set: function (value) {
  49162. this._shadowMinZ = value;
  49163. this.forceProjectionMatrixCompute();
  49164. },
  49165. enumerable: true,
  49166. configurable: true
  49167. });
  49168. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49169. /**
  49170. * Sets the shadow projection clipping maximum z value.
  49171. */
  49172. get: function () {
  49173. return this._shadowMaxZ;
  49174. },
  49175. /**
  49176. * Gets the shadow projection clipping maximum z value.
  49177. */
  49178. set: function (value) {
  49179. this._shadowMaxZ = value;
  49180. this.forceProjectionMatrixCompute();
  49181. },
  49182. enumerable: true,
  49183. configurable: true
  49184. });
  49185. /**
  49186. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49187. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49188. */
  49189. ShadowLight.prototype.computeTransformedInformation = function () {
  49190. if (this.parent && this.parent.getWorldMatrix) {
  49191. if (!this.transformedPosition) {
  49192. this.transformedPosition = BABYLON.Vector3.Zero();
  49193. }
  49194. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49195. // In case the direction is present.
  49196. if (this.direction) {
  49197. if (!this.transformedDirection) {
  49198. this.transformedDirection = BABYLON.Vector3.Zero();
  49199. }
  49200. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49201. }
  49202. return true;
  49203. }
  49204. return false;
  49205. };
  49206. /**
  49207. * Return the depth scale used for the shadow map.
  49208. * @returns the depth scale.
  49209. */
  49210. ShadowLight.prototype.getDepthScale = function () {
  49211. return 50.0;
  49212. };
  49213. /**
  49214. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49215. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49216. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49217. */
  49218. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49219. return this.transformedDirection ? this.transformedDirection : this.direction;
  49220. };
  49221. /**
  49222. * Returns the ShadowLight absolute position in the World.
  49223. * @returns the position vector in world space
  49224. */
  49225. ShadowLight.prototype.getAbsolutePosition = function () {
  49226. return this.transformedPosition ? this.transformedPosition : this.position;
  49227. };
  49228. /**
  49229. * Sets the ShadowLight direction toward the passed target.
  49230. * @param target The point tot target in local space
  49231. * @returns the updated ShadowLight direction
  49232. */
  49233. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49234. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49235. return this.direction;
  49236. };
  49237. /**
  49238. * Returns the light rotation in euler definition.
  49239. * @returns the x y z rotation in local space.
  49240. */
  49241. ShadowLight.prototype.getRotation = function () {
  49242. this.direction.normalize();
  49243. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49244. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49245. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49246. };
  49247. /**
  49248. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49249. * @returns true if a cube texture needs to be use
  49250. */
  49251. ShadowLight.prototype.needCube = function () {
  49252. return false;
  49253. };
  49254. /**
  49255. * Detects if the projection matrix requires to be recomputed this frame.
  49256. * @returns true if it requires to be recomputed otherwise, false.
  49257. */
  49258. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49259. return this._needProjectionMatrixCompute;
  49260. };
  49261. /**
  49262. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49263. */
  49264. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49265. this._needProjectionMatrixCompute = true;
  49266. };
  49267. /**
  49268. * Get the world matrix of the sahdow lights.
  49269. * @hidden Internal Use Only
  49270. */
  49271. ShadowLight.prototype._getWorldMatrix = function () {
  49272. if (!this._worldMatrix) {
  49273. this._worldMatrix = BABYLON.Matrix.Identity();
  49274. }
  49275. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49276. return this._worldMatrix;
  49277. };
  49278. /**
  49279. * Gets the minZ used for shadow according to both the scene and the light.
  49280. * @param activeCamera The camera we are returning the min for
  49281. * @returns the depth min z
  49282. */
  49283. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49284. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49285. };
  49286. /**
  49287. * Gets the maxZ used for shadow according to both the scene and the light.
  49288. * @param activeCamera The camera we are returning the max for
  49289. * @returns the depth max z
  49290. */
  49291. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49292. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49293. };
  49294. /**
  49295. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49296. * @param matrix The materix to updated with the projection information
  49297. * @param viewMatrix The transform matrix of the light
  49298. * @param renderList The list of mesh to render in the map
  49299. * @returns The current light
  49300. */
  49301. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49302. if (this.customProjectionMatrixBuilder) {
  49303. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49304. }
  49305. else {
  49306. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49307. }
  49308. return this;
  49309. };
  49310. __decorate([
  49311. BABYLON.serializeAsVector3()
  49312. ], ShadowLight.prototype, "position", null);
  49313. __decorate([
  49314. BABYLON.serializeAsVector3()
  49315. ], ShadowLight.prototype, "direction", null);
  49316. __decorate([
  49317. BABYLON.serialize()
  49318. ], ShadowLight.prototype, "shadowMinZ", null);
  49319. __decorate([
  49320. BABYLON.serialize()
  49321. ], ShadowLight.prototype, "shadowMaxZ", null);
  49322. return ShadowLight;
  49323. }(BABYLON.Light));
  49324. BABYLON.ShadowLight = ShadowLight;
  49325. })(BABYLON || (BABYLON = {}));
  49326. //# sourceMappingURL=babylon.shadowLight.js.map
  49327. var BABYLON;
  49328. (function (BABYLON) {
  49329. /**
  49330. * A point light is a light defined by an unique point in world space.
  49331. * The light is emitted in every direction from this point.
  49332. * A good example of a point light is a standard light bulb.
  49333. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49334. */
  49335. var PointLight = /** @class */ (function (_super) {
  49336. __extends(PointLight, _super);
  49337. /**
  49338. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49339. * A PointLight emits the light in every direction.
  49340. * It can cast shadows.
  49341. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49342. * ```javascript
  49343. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49344. * ```
  49345. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49346. * @param name The light friendly name
  49347. * @param position The position of the point light in the scene
  49348. * @param scene The scene the lights belongs to
  49349. */
  49350. function PointLight(name, position, scene) {
  49351. var _this = _super.call(this, name, scene) || this;
  49352. _this._shadowAngle = Math.PI / 2;
  49353. _this.position = position;
  49354. return _this;
  49355. }
  49356. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49357. /**
  49358. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49359. * This specifies what angle the shadow will use to be created.
  49360. *
  49361. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49362. */
  49363. get: function () {
  49364. return this._shadowAngle;
  49365. },
  49366. /**
  49367. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49368. * This specifies what angle the shadow will use to be created.
  49369. *
  49370. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49371. */
  49372. set: function (value) {
  49373. this._shadowAngle = value;
  49374. this.forceProjectionMatrixCompute();
  49375. },
  49376. enumerable: true,
  49377. configurable: true
  49378. });
  49379. Object.defineProperty(PointLight.prototype, "direction", {
  49380. /**
  49381. * Gets the direction if it has been set.
  49382. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49383. */
  49384. get: function () {
  49385. return this._direction;
  49386. },
  49387. /**
  49388. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49389. */
  49390. set: function (value) {
  49391. var previousNeedCube = this.needCube();
  49392. this._direction = value;
  49393. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49394. this._shadowGenerator.recreateShadowMap();
  49395. }
  49396. },
  49397. enumerable: true,
  49398. configurable: true
  49399. });
  49400. /**
  49401. * Returns the string "PointLight"
  49402. * @returns the class name
  49403. */
  49404. PointLight.prototype.getClassName = function () {
  49405. return "PointLight";
  49406. };
  49407. /**
  49408. * Returns the integer 0.
  49409. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49410. */
  49411. PointLight.prototype.getTypeID = function () {
  49412. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49413. };
  49414. /**
  49415. * Specifies wether or not the shadowmap should be a cube texture.
  49416. * @returns true if the shadowmap needs to be a cube texture.
  49417. */
  49418. PointLight.prototype.needCube = function () {
  49419. return !this.direction;
  49420. };
  49421. /**
  49422. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49423. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49424. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49425. */
  49426. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49427. if (this.direction) {
  49428. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49429. }
  49430. else {
  49431. switch (faceIndex) {
  49432. case 0:
  49433. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49434. case 1:
  49435. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49436. case 2:
  49437. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49438. case 3:
  49439. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49440. case 4:
  49441. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49442. case 5:
  49443. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49444. }
  49445. }
  49446. return BABYLON.Vector3.Zero();
  49447. };
  49448. /**
  49449. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49450. * - fov = PI / 2
  49451. * - aspect ratio : 1.0
  49452. * - z-near and far equal to the active camera minZ and maxZ.
  49453. * Returns the PointLight.
  49454. */
  49455. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49456. var activeCamera = this.getScene().activeCamera;
  49457. if (!activeCamera) {
  49458. return;
  49459. }
  49460. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49461. };
  49462. PointLight.prototype._buildUniformLayout = function () {
  49463. this._uniformBuffer.addUniform("vLightData", 4);
  49464. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49465. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49466. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49467. this._uniformBuffer.addUniform("depthValues", 2);
  49468. this._uniformBuffer.create();
  49469. };
  49470. /**
  49471. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49472. * @param effect The effect to update
  49473. * @param lightIndex The index of the light in the effect to update
  49474. * @returns The point light
  49475. */
  49476. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49477. if (this.computeTransformedInformation()) {
  49478. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49479. return this;
  49480. }
  49481. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49482. return this;
  49483. };
  49484. __decorate([
  49485. BABYLON.serialize()
  49486. ], PointLight.prototype, "shadowAngle", null);
  49487. return PointLight;
  49488. }(BABYLON.ShadowLight));
  49489. BABYLON.PointLight = PointLight;
  49490. })(BABYLON || (BABYLON = {}));
  49491. //# sourceMappingURL=babylon.pointLight.js.map
  49492. var BABYLON;
  49493. (function (BABYLON) {
  49494. /**
  49495. * A directional light is defined by a direction (what a surprise!).
  49496. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49497. * 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.
  49498. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49499. */
  49500. var DirectionalLight = /** @class */ (function (_super) {
  49501. __extends(DirectionalLight, _super);
  49502. /**
  49503. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49504. * The directional light is emitted from everywhere in the given direction.
  49505. * It can cast shawdows.
  49506. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49507. * @param name The friendly name of the light
  49508. * @param direction The direction of the light
  49509. * @param scene The scene the light belongs to
  49510. */
  49511. function DirectionalLight(name, direction, scene) {
  49512. var _this = _super.call(this, name, scene) || this;
  49513. _this._shadowFrustumSize = 0;
  49514. _this._shadowOrthoScale = 0.1;
  49515. /**
  49516. * Automatically compute the projection matrix to best fit (including all the casters)
  49517. * on each frame.
  49518. */
  49519. _this.autoUpdateExtends = true;
  49520. // Cache
  49521. _this._orthoLeft = Number.MAX_VALUE;
  49522. _this._orthoRight = Number.MIN_VALUE;
  49523. _this._orthoTop = Number.MIN_VALUE;
  49524. _this._orthoBottom = Number.MAX_VALUE;
  49525. _this.position = direction.scale(-1.0);
  49526. _this.direction = direction;
  49527. return _this;
  49528. }
  49529. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49530. /**
  49531. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49532. */
  49533. get: function () {
  49534. return this._shadowFrustumSize;
  49535. },
  49536. /**
  49537. * Specifies a fix frustum size for the shadow generation.
  49538. */
  49539. set: function (value) {
  49540. this._shadowFrustumSize = value;
  49541. this.forceProjectionMatrixCompute();
  49542. },
  49543. enumerable: true,
  49544. configurable: true
  49545. });
  49546. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49547. /**
  49548. * Gets the shadow projection scale against the optimal computed one.
  49549. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49550. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49551. */
  49552. get: function () {
  49553. return this._shadowOrthoScale;
  49554. },
  49555. /**
  49556. * Sets the shadow projection scale against the optimal computed one.
  49557. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49558. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49559. */
  49560. set: function (value) {
  49561. this._shadowOrthoScale = value;
  49562. this.forceProjectionMatrixCompute();
  49563. },
  49564. enumerable: true,
  49565. configurable: true
  49566. });
  49567. /**
  49568. * Returns the string "DirectionalLight".
  49569. * @return The class name
  49570. */
  49571. DirectionalLight.prototype.getClassName = function () {
  49572. return "DirectionalLight";
  49573. };
  49574. /**
  49575. * Returns the integer 1.
  49576. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49577. */
  49578. DirectionalLight.prototype.getTypeID = function () {
  49579. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49580. };
  49581. /**
  49582. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49583. * Returns the DirectionalLight Shadow projection matrix.
  49584. */
  49585. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49586. if (this.shadowFrustumSize > 0) {
  49587. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49588. }
  49589. else {
  49590. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49591. }
  49592. };
  49593. /**
  49594. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49595. * Returns the DirectionalLight Shadow projection matrix.
  49596. */
  49597. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49598. var activeCamera = this.getScene().activeCamera;
  49599. if (!activeCamera) {
  49600. return;
  49601. }
  49602. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49603. };
  49604. /**
  49605. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49606. * Returns the DirectionalLight Shadow projection matrix.
  49607. */
  49608. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49609. var activeCamera = this.getScene().activeCamera;
  49610. if (!activeCamera) {
  49611. return;
  49612. }
  49613. // Check extends
  49614. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49615. var tempVector3 = BABYLON.Vector3.Zero();
  49616. this._orthoLeft = Number.MAX_VALUE;
  49617. this._orthoRight = Number.MIN_VALUE;
  49618. this._orthoTop = Number.MIN_VALUE;
  49619. this._orthoBottom = Number.MAX_VALUE;
  49620. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49621. var mesh = renderList[meshIndex];
  49622. if (!mesh) {
  49623. continue;
  49624. }
  49625. var boundingInfo = mesh.getBoundingInfo();
  49626. var boundingBox = boundingInfo.boundingBox;
  49627. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49628. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49629. if (tempVector3.x < this._orthoLeft)
  49630. this._orthoLeft = tempVector3.x;
  49631. if (tempVector3.y < this._orthoBottom)
  49632. this._orthoBottom = tempVector3.y;
  49633. if (tempVector3.x > this._orthoRight)
  49634. this._orthoRight = tempVector3.x;
  49635. if (tempVector3.y > this._orthoTop)
  49636. this._orthoTop = tempVector3.y;
  49637. }
  49638. }
  49639. }
  49640. var xOffset = this._orthoRight - this._orthoLeft;
  49641. var yOffset = this._orthoTop - this._orthoBottom;
  49642. 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);
  49643. };
  49644. DirectionalLight.prototype._buildUniformLayout = function () {
  49645. this._uniformBuffer.addUniform("vLightData", 4);
  49646. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49647. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49648. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49649. this._uniformBuffer.addUniform("depthValues", 2);
  49650. this._uniformBuffer.create();
  49651. };
  49652. /**
  49653. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49654. * @param effect The effect to update
  49655. * @param lightIndex The index of the light in the effect to update
  49656. * @returns The directional light
  49657. */
  49658. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49659. if (this.computeTransformedInformation()) {
  49660. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49661. return this;
  49662. }
  49663. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49664. return this;
  49665. };
  49666. /**
  49667. * Gets the minZ used for shadow according to both the scene and the light.
  49668. *
  49669. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49670. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49671. * @param activeCamera The camera we are returning the min for
  49672. * @returns the depth min z
  49673. */
  49674. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49675. return 1;
  49676. };
  49677. /**
  49678. * Gets the maxZ used for shadow according to both the scene and the light.
  49679. *
  49680. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49681. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49682. * @param activeCamera The camera we are returning the max for
  49683. * @returns the depth max z
  49684. */
  49685. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49686. return 1;
  49687. };
  49688. __decorate([
  49689. BABYLON.serialize()
  49690. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49691. __decorate([
  49692. BABYLON.serialize()
  49693. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49694. __decorate([
  49695. BABYLON.serialize()
  49696. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49697. return DirectionalLight;
  49698. }(BABYLON.ShadowLight));
  49699. BABYLON.DirectionalLight = DirectionalLight;
  49700. })(BABYLON || (BABYLON = {}));
  49701. //# sourceMappingURL=babylon.directionalLight.js.map
  49702. var BABYLON;
  49703. (function (BABYLON) {
  49704. /**
  49705. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49706. * These values define a cone of light starting from the position, emitting toward the direction.
  49707. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49708. * and the exponent defines the speed of the decay of the light with distance (reach).
  49709. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49710. */
  49711. var SpotLight = /** @class */ (function (_super) {
  49712. __extends(SpotLight, _super);
  49713. /**
  49714. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49715. * It can cast shadows.
  49716. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49717. * @param name The light friendly name
  49718. * @param position The position of the spot light in the scene
  49719. * @param direction The direction of the light in the scene
  49720. * @param angle The cone angle of the light in Radians
  49721. * @param exponent The light decay speed with the distance from the emission spot
  49722. * @param scene The scene the lights belongs to
  49723. */
  49724. function SpotLight(name, position, direction, angle, exponent, scene) {
  49725. var _this = _super.call(this, name, scene) || this;
  49726. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49727. _this._projectionTextureLightNear = 1e-6;
  49728. _this._projectionTextureLightFar = 1000.0;
  49729. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49730. _this._projectionTextureViewLightDirty = true;
  49731. _this._projectionTextureProjectionLightDirty = true;
  49732. _this._projectionTextureDirty = true;
  49733. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49734. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49735. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49736. _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);
  49737. _this.position = position;
  49738. _this.direction = direction;
  49739. _this.angle = angle;
  49740. _this.exponent = exponent;
  49741. return _this;
  49742. }
  49743. Object.defineProperty(SpotLight.prototype, "angle", {
  49744. /**
  49745. * Gets the cone angle of the spot light in Radians.
  49746. */
  49747. get: function () {
  49748. return this._angle;
  49749. },
  49750. /**
  49751. * Sets the cone angle of the spot light in Radians.
  49752. */
  49753. set: function (value) {
  49754. this._angle = value;
  49755. this._projectionTextureProjectionLightDirty = true;
  49756. this.forceProjectionMatrixCompute();
  49757. },
  49758. enumerable: true,
  49759. configurable: true
  49760. });
  49761. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49762. /**
  49763. * Allows scaling the angle of the light for shadow generation only.
  49764. */
  49765. get: function () {
  49766. return this._shadowAngleScale;
  49767. },
  49768. /**
  49769. * Allows scaling the angle of the light for shadow generation only.
  49770. */
  49771. set: function (value) {
  49772. this._shadowAngleScale = value;
  49773. this.forceProjectionMatrixCompute();
  49774. },
  49775. enumerable: true,
  49776. configurable: true
  49777. });
  49778. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49779. /**
  49780. * Allows reading the projecton texture
  49781. */
  49782. get: function () {
  49783. return this._projectionTextureMatrix;
  49784. },
  49785. enumerable: true,
  49786. configurable: true
  49787. });
  49788. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49789. /**
  49790. * Gets the near clip of the Spotlight for texture projection.
  49791. */
  49792. get: function () {
  49793. return this._projectionTextureLightNear;
  49794. },
  49795. /**
  49796. * Sets the near clip of the Spotlight for texture projection.
  49797. */
  49798. set: function (value) {
  49799. this._projectionTextureLightNear = value;
  49800. this._projectionTextureProjectionLightDirty = true;
  49801. },
  49802. enumerable: true,
  49803. configurable: true
  49804. });
  49805. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49806. /**
  49807. * Gets the far clip of the Spotlight for texture projection.
  49808. */
  49809. get: function () {
  49810. return this._projectionTextureLightFar;
  49811. },
  49812. /**
  49813. * Sets the far clip of the Spotlight for texture projection.
  49814. */
  49815. set: function (value) {
  49816. this._projectionTextureLightFar = value;
  49817. this._projectionTextureProjectionLightDirty = true;
  49818. },
  49819. enumerable: true,
  49820. configurable: true
  49821. });
  49822. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49823. /**
  49824. * Gets the Up vector of the Spotlight for texture projection.
  49825. */
  49826. get: function () {
  49827. return this._projectionTextureUpDirection;
  49828. },
  49829. /**
  49830. * Sets the Up vector of the Spotlight for texture projection.
  49831. */
  49832. set: function (value) {
  49833. this._projectionTextureUpDirection = value;
  49834. this._projectionTextureProjectionLightDirty = true;
  49835. },
  49836. enumerable: true,
  49837. configurable: true
  49838. });
  49839. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49840. /**
  49841. * Gets the projection texture of the light.
  49842. */
  49843. get: function () {
  49844. return this._projectionTexture;
  49845. },
  49846. /**
  49847. * Sets the projection texture of the light.
  49848. */
  49849. set: function (value) {
  49850. this._projectionTexture = value;
  49851. this._projectionTextureDirty = true;
  49852. },
  49853. enumerable: true,
  49854. configurable: true
  49855. });
  49856. /**
  49857. * Returns the string "SpotLight".
  49858. * @returns the class name
  49859. */
  49860. SpotLight.prototype.getClassName = function () {
  49861. return "SpotLight";
  49862. };
  49863. /**
  49864. * Returns the integer 2.
  49865. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49866. */
  49867. SpotLight.prototype.getTypeID = function () {
  49868. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49869. };
  49870. /**
  49871. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49872. */
  49873. SpotLight.prototype._setDirection = function (value) {
  49874. _super.prototype._setDirection.call(this, value);
  49875. this._projectionTextureViewLightDirty = true;
  49876. };
  49877. /**
  49878. * Overrides the position setter to recompute the projection texture view light Matrix.
  49879. */
  49880. SpotLight.prototype._setPosition = function (value) {
  49881. _super.prototype._setPosition.call(this, value);
  49882. this._projectionTextureViewLightDirty = true;
  49883. };
  49884. /**
  49885. * 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.
  49886. * Returns the SpotLight.
  49887. */
  49888. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49889. var activeCamera = this.getScene().activeCamera;
  49890. if (!activeCamera) {
  49891. return;
  49892. }
  49893. this._shadowAngleScale = this._shadowAngleScale || 1;
  49894. var angle = this._shadowAngleScale * this._angle;
  49895. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49896. };
  49897. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49898. this._projectionTextureViewLightDirty = false;
  49899. this._projectionTextureDirty = true;
  49900. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49901. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49902. };
  49903. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49904. this._projectionTextureProjectionLightDirty = false;
  49905. this._projectionTextureDirty = true;
  49906. var light_far = this.projectionTextureLightFar;
  49907. var light_near = this.projectionTextureLightNear;
  49908. var P = light_far / (light_far - light_near);
  49909. var Q = -P * light_near;
  49910. var S = 1.0 / Math.tan(this._angle / 2.0);
  49911. var A = 1.0;
  49912. 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);
  49913. };
  49914. /**
  49915. * Main function for light texture projection matrix computing.
  49916. */
  49917. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49918. this._projectionTextureDirty = false;
  49919. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49920. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49921. };
  49922. SpotLight.prototype._buildUniformLayout = function () {
  49923. this._uniformBuffer.addUniform("vLightData", 4);
  49924. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49925. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49926. this._uniformBuffer.addUniform("vLightDirection", 3);
  49927. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49928. this._uniformBuffer.addUniform("depthValues", 2);
  49929. this._uniformBuffer.create();
  49930. };
  49931. /**
  49932. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49933. * @param effect The effect to update
  49934. * @param lightIndex The index of the light in the effect to update
  49935. * @returns The spot light
  49936. */
  49937. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49938. var normalizeDirection;
  49939. if (this.computeTransformedInformation()) {
  49940. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49941. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49942. }
  49943. else {
  49944. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49945. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49946. }
  49947. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49948. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49949. if (this._projectionTextureViewLightDirty) {
  49950. this._computeProjectionTextureViewLightMatrix();
  49951. }
  49952. if (this._projectionTextureProjectionLightDirty) {
  49953. this._computeProjectionTextureProjectionLightMatrix();
  49954. }
  49955. if (this._projectionTextureDirty) {
  49956. this._computeProjectionTextureMatrix();
  49957. }
  49958. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49959. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49960. }
  49961. return this;
  49962. };
  49963. /**
  49964. * Disposes the light and the associated resources.
  49965. */
  49966. SpotLight.prototype.dispose = function () {
  49967. _super.prototype.dispose.call(this);
  49968. if (this._projectionTexture) {
  49969. this._projectionTexture.dispose();
  49970. }
  49971. };
  49972. __decorate([
  49973. BABYLON.serialize()
  49974. ], SpotLight.prototype, "angle", null);
  49975. __decorate([
  49976. BABYLON.serialize()
  49977. ], SpotLight.prototype, "shadowAngleScale", null);
  49978. __decorate([
  49979. BABYLON.serialize()
  49980. ], SpotLight.prototype, "exponent", void 0);
  49981. __decorate([
  49982. BABYLON.serialize()
  49983. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49984. __decorate([
  49985. BABYLON.serialize()
  49986. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49987. __decorate([
  49988. BABYLON.serialize()
  49989. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49990. __decorate([
  49991. BABYLON.serializeAsTexture("projectedLightTexture")
  49992. ], SpotLight.prototype, "_projectionTexture", void 0);
  49993. return SpotLight;
  49994. }(BABYLON.ShadowLight));
  49995. BABYLON.SpotLight = SpotLight;
  49996. })(BABYLON || (BABYLON = {}));
  49997. //# sourceMappingURL=babylon.spotLight.js.map
  49998. var BABYLON;
  49999. (function (BABYLON) {
  50000. /**
  50001. * Class used to override all child animations of a given target
  50002. */
  50003. var AnimationPropertiesOverride = /** @class */ (function () {
  50004. function AnimationPropertiesOverride() {
  50005. /**
  50006. * Gets or sets a value indicating if animation blending must be used
  50007. */
  50008. this.enableBlending = false;
  50009. /**
  50010. * Gets or sets the blending speed to use when enableBlending is true
  50011. */
  50012. this.blendingSpeed = 0.01;
  50013. /**
  50014. * Gets or sets the default loop mode to use
  50015. */
  50016. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50017. }
  50018. return AnimationPropertiesOverride;
  50019. }());
  50020. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50021. })(BABYLON || (BABYLON = {}));
  50022. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50023. var BABYLON;
  50024. (function (BABYLON) {
  50025. /**
  50026. * Represents the range of an animation
  50027. */
  50028. var AnimationRange = /** @class */ (function () {
  50029. /**
  50030. * Initializes the range of an animation
  50031. * @param name The name of the animation range
  50032. * @param from The starting frame of the animation
  50033. * @param to The ending frame of the animation
  50034. */
  50035. function AnimationRange(
  50036. /**The name of the animation range**/
  50037. name,
  50038. /**The starting frame of the animation */
  50039. from,
  50040. /**The ending frame of the animation*/
  50041. to) {
  50042. this.name = name;
  50043. this.from = from;
  50044. this.to = to;
  50045. }
  50046. /**
  50047. * Makes a copy of the animation range
  50048. * @returns A copy of the animation range
  50049. */
  50050. AnimationRange.prototype.clone = function () {
  50051. return new AnimationRange(this.name, this.from, this.to);
  50052. };
  50053. return AnimationRange;
  50054. }());
  50055. BABYLON.AnimationRange = AnimationRange;
  50056. /**
  50057. * Composed of a frame, and an action function
  50058. */
  50059. var AnimationEvent = /** @class */ (function () {
  50060. /**
  50061. * Initializes the animation event
  50062. * @param frame The frame for which the event is triggered
  50063. * @param action The event to perform when triggered
  50064. * @param onlyOnce Specifies if the event should be triggered only once
  50065. */
  50066. function AnimationEvent(
  50067. /** The frame for which the event is triggered **/
  50068. frame,
  50069. /** The event to perform when triggered **/
  50070. action,
  50071. /** Specifies if the event should be triggered only once**/
  50072. onlyOnce) {
  50073. this.frame = frame;
  50074. this.action = action;
  50075. this.onlyOnce = onlyOnce;
  50076. /**
  50077. * Specifies if the animation event is done
  50078. */
  50079. this.isDone = false;
  50080. }
  50081. return AnimationEvent;
  50082. }());
  50083. BABYLON.AnimationEvent = AnimationEvent;
  50084. /**
  50085. * A cursor which tracks a point on a path
  50086. */
  50087. var PathCursor = /** @class */ (function () {
  50088. /**
  50089. * Initializes the path cursor
  50090. * @param path The path to track
  50091. */
  50092. function PathCursor(path) {
  50093. this.path = path;
  50094. /**
  50095. * Stores path cursor callbacks for when an onchange event is triggered
  50096. */
  50097. this._onchange = new Array();
  50098. /**
  50099. * The value of the path cursor
  50100. */
  50101. this.value = 0;
  50102. /**
  50103. * The animation array of the path cursor
  50104. */
  50105. this.animations = new Array();
  50106. }
  50107. /**
  50108. * Gets the cursor point on the path
  50109. * @returns A point on the path cursor at the cursor location
  50110. */
  50111. PathCursor.prototype.getPoint = function () {
  50112. var point = this.path.getPointAtLengthPosition(this.value);
  50113. return new BABYLON.Vector3(point.x, 0, point.y);
  50114. };
  50115. /**
  50116. * Moves the cursor ahead by the step amount
  50117. * @param step The amount to move the cursor forward
  50118. * @returns This path cursor
  50119. */
  50120. PathCursor.prototype.moveAhead = function (step) {
  50121. if (step === void 0) { step = 0.002; }
  50122. this.move(step);
  50123. return this;
  50124. };
  50125. /**
  50126. * Moves the cursor behind by the step amount
  50127. * @param step The amount to move the cursor back
  50128. * @returns This path cursor
  50129. */
  50130. PathCursor.prototype.moveBack = function (step) {
  50131. if (step === void 0) { step = 0.002; }
  50132. this.move(-step);
  50133. return this;
  50134. };
  50135. /**
  50136. * Moves the cursor by the step amount
  50137. * If the step amount is greater than one, an exception is thrown
  50138. * @param step The amount to move the cursor
  50139. * @returns This path cursor
  50140. */
  50141. PathCursor.prototype.move = function (step) {
  50142. if (Math.abs(step) > 1) {
  50143. throw "step size should be less than 1.";
  50144. }
  50145. this.value += step;
  50146. this.ensureLimits();
  50147. this.raiseOnChange();
  50148. return this;
  50149. };
  50150. /**
  50151. * Ensures that the value is limited between zero and one
  50152. * @returns This path cursor
  50153. */
  50154. PathCursor.prototype.ensureLimits = function () {
  50155. while (this.value > 1) {
  50156. this.value -= 1;
  50157. }
  50158. while (this.value < 0) {
  50159. this.value += 1;
  50160. }
  50161. return this;
  50162. };
  50163. /**
  50164. * Runs onchange callbacks on change (used by the animation engine)
  50165. * @returns This path cursor
  50166. */
  50167. PathCursor.prototype.raiseOnChange = function () {
  50168. var _this = this;
  50169. this._onchange.forEach(function (f) { return f(_this); });
  50170. return this;
  50171. };
  50172. /**
  50173. * Executes a function on change
  50174. * @param f A path cursor onchange callback
  50175. * @returns This path cursor
  50176. */
  50177. PathCursor.prototype.onchange = function (f) {
  50178. this._onchange.push(f);
  50179. return this;
  50180. };
  50181. return PathCursor;
  50182. }());
  50183. BABYLON.PathCursor = PathCursor;
  50184. /**
  50185. * Enum for the animation key frame interpolation type
  50186. */
  50187. var AnimationKeyInterpolation;
  50188. (function (AnimationKeyInterpolation) {
  50189. /**
  50190. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50191. */
  50192. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50193. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50194. /**
  50195. * Class used to store any kind of animation
  50196. */
  50197. var Animation = /** @class */ (function () {
  50198. /**
  50199. * Initializes the animation
  50200. * @param name Name of the animation
  50201. * @param targetProperty Property to animate
  50202. * @param framePerSecond The frames per second of the animation
  50203. * @param dataType The data type of the animation
  50204. * @param loopMode The loop mode of the animation
  50205. * @param enableBlendings Specifies if blending should be enabled
  50206. */
  50207. function Animation(
  50208. /**Name of the animation */
  50209. name,
  50210. /**Property to animate */
  50211. targetProperty,
  50212. /**The frames per second of the animation */
  50213. framePerSecond,
  50214. /**The data type of the animation */
  50215. dataType,
  50216. /**The loop mode of the animation */
  50217. loopMode,
  50218. /**Specifies if blending should be enabled */
  50219. enableBlending) {
  50220. this.name = name;
  50221. this.targetProperty = targetProperty;
  50222. this.framePerSecond = framePerSecond;
  50223. this.dataType = dataType;
  50224. this.loopMode = loopMode;
  50225. this.enableBlending = enableBlending;
  50226. /**
  50227. * @hidden Internal use only
  50228. */
  50229. this._runtimeAnimations = new Array();
  50230. /**
  50231. * The set of event that will be linked to this animation
  50232. */
  50233. this._events = new Array();
  50234. /**
  50235. * Stores the blending speed of the animation
  50236. */
  50237. this.blendingSpeed = 0.01;
  50238. /**
  50239. * Stores the animation ranges for the animation
  50240. */
  50241. this._ranges = {};
  50242. this.targetPropertyPath = targetProperty.split(".");
  50243. this.dataType = dataType;
  50244. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50245. }
  50246. /**
  50247. * @hidden Internal use
  50248. */
  50249. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50250. var dataType = undefined;
  50251. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50252. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50253. }
  50254. else if (from instanceof BABYLON.Quaternion) {
  50255. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50256. }
  50257. else if (from instanceof BABYLON.Vector3) {
  50258. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50259. }
  50260. else if (from instanceof BABYLON.Vector2) {
  50261. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50262. }
  50263. else if (from instanceof BABYLON.Color3) {
  50264. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50265. }
  50266. else if (from instanceof BABYLON.Size) {
  50267. dataType = Animation.ANIMATIONTYPE_SIZE;
  50268. }
  50269. if (dataType == undefined) {
  50270. return null;
  50271. }
  50272. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50273. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50274. animation.setKeys(keys);
  50275. if (easingFunction !== undefined) {
  50276. animation.setEasingFunction(easingFunction);
  50277. }
  50278. return animation;
  50279. };
  50280. /**
  50281. * Sets up an animation
  50282. * @param property The property to animate
  50283. * @param animationType The animation type to apply
  50284. * @param framePerSecond The frames per second of the animation
  50285. * @param easingFunction The easing function used in the animation
  50286. * @returns The created animation
  50287. */
  50288. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50289. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50290. animation.setEasingFunction(easingFunction);
  50291. return animation;
  50292. };
  50293. /**
  50294. * Create and start an animation on a node
  50295. * @param name defines the name of the global animation that will be run on all nodes
  50296. * @param node defines the root node where the animation will take place
  50297. * @param targetProperty defines property to animate
  50298. * @param framePerSecond defines the number of frame per second yo use
  50299. * @param totalFrame defines the number of frames in total
  50300. * @param from defines the initial value
  50301. * @param to defines the final value
  50302. * @param loopMode defines which loop mode you want to use (off by default)
  50303. * @param easingFunction defines the easing function to use (linear by default)
  50304. * @param onAnimationEnd defines the callback to call when animation end
  50305. * @returns the animatable created for this animation
  50306. */
  50307. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50308. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50309. if (!animation) {
  50310. return null;
  50311. }
  50312. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50313. };
  50314. /**
  50315. * Create and start an animation on a node and its descendants
  50316. * @param name defines the name of the global animation that will be run on all nodes
  50317. * @param node defines the root node where the animation will take place
  50318. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  50319. * @param targetProperty defines property to animate
  50320. * @param framePerSecond defines the number of frame per second to use
  50321. * @param totalFrame defines the number of frames in total
  50322. * @param from defines the initial value
  50323. * @param to defines the final value
  50324. * @param loopMode defines which loop mode you want to use (off by default)
  50325. * @param easingFunction defines the easing function to use (linear by default)
  50326. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50327. * @returns the list of animatables created for all nodes
  50328. * @example https://www.babylonjs-playground.com/#MH0VLI
  50329. */
  50330. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50331. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50332. if (!animation) {
  50333. return null;
  50334. }
  50335. var scene = node.getScene();
  50336. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50337. };
  50338. /**
  50339. * Creates a new animation, merges it with the existing animations and starts it
  50340. * @param name Name of the animation
  50341. * @param node Node which contains the scene that begins the animations
  50342. * @param targetProperty Specifies which property to animate
  50343. * @param framePerSecond The frames per second of the animation
  50344. * @param totalFrame The total number of frames
  50345. * @param from The frame at the beginning of the animation
  50346. * @param to The frame at the end of the animation
  50347. * @param loopMode Specifies the loop mode of the animation
  50348. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50349. * @param onAnimationEnd Callback to run once the animation is complete
  50350. * @returns Nullable animation
  50351. */
  50352. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50353. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50354. if (!animation) {
  50355. return null;
  50356. }
  50357. node.animations.push(animation);
  50358. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50359. };
  50360. /**
  50361. * Transition property of the Camera to the target Value
  50362. * @param property The property to transition
  50363. * @param targetValue The target Value of the property
  50364. * @param host The object where the property to animate belongs
  50365. * @param scene Scene used to run the animation
  50366. * @param frameRate Framerate (in frame/s) to use
  50367. * @param transition The transition type we want to use
  50368. * @param duration The duration of the animation, in milliseconds
  50369. * @param onAnimationEnd Callback trigger at the end of the animation
  50370. * @returns Nullable animation
  50371. */
  50372. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50373. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50374. if (duration <= 0) {
  50375. host[property] = targetValue;
  50376. if (onAnimationEnd) {
  50377. onAnimationEnd();
  50378. }
  50379. return null;
  50380. }
  50381. var endFrame = frameRate * (duration / 1000);
  50382. transition.setKeys([{
  50383. frame: 0,
  50384. value: host[property].clone ? host[property].clone() : host[property]
  50385. },
  50386. {
  50387. frame: endFrame,
  50388. value: targetValue
  50389. }]);
  50390. if (!host.animations) {
  50391. host.animations = [];
  50392. }
  50393. host.animations.push(transition);
  50394. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50395. animation.onAnimationEnd = onAnimationEnd;
  50396. return animation;
  50397. };
  50398. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50399. /**
  50400. * Return the array of runtime animations currently using this animation
  50401. */
  50402. get: function () {
  50403. return this._runtimeAnimations;
  50404. },
  50405. enumerable: true,
  50406. configurable: true
  50407. });
  50408. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50409. /**
  50410. * Specifies if any of the runtime animations are currently running
  50411. */
  50412. get: function () {
  50413. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50414. var runtimeAnimation = _a[_i];
  50415. if (!runtimeAnimation.isStopped) {
  50416. return true;
  50417. }
  50418. }
  50419. return false;
  50420. },
  50421. enumerable: true,
  50422. configurable: true
  50423. });
  50424. // Methods
  50425. /**
  50426. * Converts the animation to a string
  50427. * @param fullDetails support for multiple levels of logging within scene loading
  50428. * @returns String form of the animation
  50429. */
  50430. Animation.prototype.toString = function (fullDetails) {
  50431. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50432. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50433. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50434. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50435. if (fullDetails) {
  50436. ret += ", Ranges: {";
  50437. var first = true;
  50438. for (var name in this._ranges) {
  50439. if (first) {
  50440. ret += ", ";
  50441. first = false;
  50442. }
  50443. ret += name;
  50444. }
  50445. ret += "}";
  50446. }
  50447. return ret;
  50448. };
  50449. /**
  50450. * Add an event to this animation
  50451. * @param event Event to add
  50452. */
  50453. Animation.prototype.addEvent = function (event) {
  50454. this._events.push(event);
  50455. };
  50456. /**
  50457. * Remove all events found at the given frame
  50458. * @param frame The frame to remove events from
  50459. */
  50460. Animation.prototype.removeEvents = function (frame) {
  50461. for (var index = 0; index < this._events.length; index++) {
  50462. if (this._events[index].frame === frame) {
  50463. this._events.splice(index, 1);
  50464. index--;
  50465. }
  50466. }
  50467. };
  50468. /**
  50469. * Retrieves all the events from the animation
  50470. * @returns Events from the animation
  50471. */
  50472. Animation.prototype.getEvents = function () {
  50473. return this._events;
  50474. };
  50475. /**
  50476. * Creates an animation range
  50477. * @param name Name of the animation range
  50478. * @param from Starting frame of the animation range
  50479. * @param to Ending frame of the animation
  50480. */
  50481. Animation.prototype.createRange = function (name, from, to) {
  50482. // check name not already in use; could happen for bones after serialized
  50483. if (!this._ranges[name]) {
  50484. this._ranges[name] = new AnimationRange(name, from, to);
  50485. }
  50486. };
  50487. /**
  50488. * Deletes an animation range by name
  50489. * @param name Name of the animation range to delete
  50490. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50491. */
  50492. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50493. if (deleteFrames === void 0) { deleteFrames = true; }
  50494. var range = this._ranges[name];
  50495. if (!range) {
  50496. return;
  50497. }
  50498. if (deleteFrames) {
  50499. var from = range.from;
  50500. var to = range.to;
  50501. // this loop MUST go high to low for multiple splices to work
  50502. for (var key = this._keys.length - 1; key >= 0; key--) {
  50503. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50504. this._keys.splice(key, 1);
  50505. }
  50506. }
  50507. }
  50508. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50509. };
  50510. /**
  50511. * Gets the animation range by name, or null if not defined
  50512. * @param name Name of the animation range
  50513. * @returns Nullable animation range
  50514. */
  50515. Animation.prototype.getRange = function (name) {
  50516. return this._ranges[name];
  50517. };
  50518. /**
  50519. * Gets the key frames from the animation
  50520. * @returns The key frames of the animation
  50521. */
  50522. Animation.prototype.getKeys = function () {
  50523. return this._keys;
  50524. };
  50525. /**
  50526. * Gets the highest frame rate of the animation
  50527. * @returns Highest frame rate of the animation
  50528. */
  50529. Animation.prototype.getHighestFrame = function () {
  50530. var ret = 0;
  50531. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50532. if (ret < this._keys[key].frame) {
  50533. ret = this._keys[key].frame;
  50534. }
  50535. }
  50536. return ret;
  50537. };
  50538. /**
  50539. * Gets the easing function of the animation
  50540. * @returns Easing function of the animation
  50541. */
  50542. Animation.prototype.getEasingFunction = function () {
  50543. return this._easingFunction;
  50544. };
  50545. /**
  50546. * Sets the easing function of the animation
  50547. * @param easingFunction A custom mathematical formula for animation
  50548. */
  50549. Animation.prototype.setEasingFunction = function (easingFunction) {
  50550. this._easingFunction = easingFunction;
  50551. };
  50552. /**
  50553. * Interpolates a scalar linearly
  50554. * @param startValue Start value of the animation curve
  50555. * @param endValue End value of the animation curve
  50556. * @param gradient Scalar amount to interpolate
  50557. * @returns Interpolated scalar value
  50558. */
  50559. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50560. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50561. };
  50562. /**
  50563. * Interpolates a scalar cubically
  50564. * @param startValue Start value of the animation curve
  50565. * @param outTangent End tangent of the animation
  50566. * @param endValue End value of the animation curve
  50567. * @param inTangent Start tangent of the animation curve
  50568. * @param gradient Scalar amount to interpolate
  50569. * @returns Interpolated scalar value
  50570. */
  50571. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50572. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50573. };
  50574. /**
  50575. * Interpolates a quaternion using a spherical linear interpolation
  50576. * @param startValue Start value of the animation curve
  50577. * @param endValue End value of the animation curve
  50578. * @param gradient Scalar amount to interpolate
  50579. * @returns Interpolated quaternion value
  50580. */
  50581. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50582. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50583. };
  50584. /**
  50585. * Interpolates a quaternion cubically
  50586. * @param startValue Start value of the animation curve
  50587. * @param outTangent End tangent of the animation curve
  50588. * @param endValue End value of the animation curve
  50589. * @param inTangent Start tangent of the animation curve
  50590. * @param gradient Scalar amount to interpolate
  50591. * @returns Interpolated quaternion value
  50592. */
  50593. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50594. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50595. };
  50596. /**
  50597. * Interpolates a Vector3 linearl
  50598. * @param startValue Start value of the animation curve
  50599. * @param endValue End value of the animation curve
  50600. * @param gradient Scalar amount to interpolate
  50601. * @returns Interpolated scalar value
  50602. */
  50603. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50604. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50605. };
  50606. /**
  50607. * Interpolates a Vector3 cubically
  50608. * @param startValue Start value of the animation curve
  50609. * @param outTangent End tangent of the animation
  50610. * @param endValue End value of the animation curve
  50611. * @param inTangent Start tangent of the animation curve
  50612. * @param gradient Scalar amount to interpolate
  50613. * @returns InterpolatedVector3 value
  50614. */
  50615. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50616. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50617. };
  50618. /**
  50619. * Interpolates a Vector2 linearly
  50620. * @param startValue Start value of the animation curve
  50621. * @param endValue End value of the animation curve
  50622. * @param gradient Scalar amount to interpolate
  50623. * @returns Interpolated Vector2 value
  50624. */
  50625. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50626. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50627. };
  50628. /**
  50629. * Interpolates a Vector2 cubically
  50630. * @param startValue Start value of the animation curve
  50631. * @param outTangent End tangent of the animation
  50632. * @param endValue End value of the animation curve
  50633. * @param inTangent Start tangent of the animation curve
  50634. * @param gradient Scalar amount to interpolate
  50635. * @returns Interpolated Vector2 value
  50636. */
  50637. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50638. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50639. };
  50640. /**
  50641. * Interpolates a size linearly
  50642. * @param startValue Start value of the animation curve
  50643. * @param endValue End value of the animation curve
  50644. * @param gradient Scalar amount to interpolate
  50645. * @returns Interpolated Size value
  50646. */
  50647. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50648. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50649. };
  50650. /**
  50651. * Interpolates a Color3 linearly
  50652. * @param startValue Start value of the animation curve
  50653. * @param endValue End value of the animation curve
  50654. * @param gradient Scalar amount to interpolate
  50655. * @returns Interpolated Color3 value
  50656. */
  50657. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50658. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50659. };
  50660. /**
  50661. * @hidden Internal use only
  50662. */
  50663. Animation.prototype._getKeyValue = function (value) {
  50664. if (typeof value === "function") {
  50665. return value();
  50666. }
  50667. return value;
  50668. };
  50669. /**
  50670. * @hidden Internal use only
  50671. */
  50672. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50673. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50674. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50675. }
  50676. var keys = this.getKeys();
  50677. // Try to get a hash to find the right key
  50678. 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));
  50679. if (keys[startKeyIndex].frame >= currentFrame) {
  50680. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50681. startKeyIndex--;
  50682. }
  50683. }
  50684. for (var key = startKeyIndex; key < keys.length; key++) {
  50685. var endKey = keys[key + 1];
  50686. if (endKey.frame >= currentFrame) {
  50687. var startKey = keys[key];
  50688. var startValue = this._getKeyValue(startKey.value);
  50689. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50690. return startValue;
  50691. }
  50692. var endValue = this._getKeyValue(endKey.value);
  50693. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50694. var frameDelta = endKey.frame - startKey.frame;
  50695. // gradient : percent of currentFrame between the frame inf and the frame sup
  50696. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50697. // check for easingFunction and correction of gradient
  50698. var easingFunction = this.getEasingFunction();
  50699. if (easingFunction != null) {
  50700. gradient = easingFunction.ease(gradient);
  50701. }
  50702. switch (this.dataType) {
  50703. // Float
  50704. case Animation.ANIMATIONTYPE_FLOAT:
  50705. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50706. switch (loopMode) {
  50707. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50708. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50709. return floatValue;
  50710. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50711. return offsetValue * repeatCount + floatValue;
  50712. }
  50713. break;
  50714. // Quaternion
  50715. case Animation.ANIMATIONTYPE_QUATERNION:
  50716. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50717. switch (loopMode) {
  50718. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50719. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50720. return quatValue;
  50721. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50722. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50723. }
  50724. return quatValue;
  50725. // Vector3
  50726. case Animation.ANIMATIONTYPE_VECTOR3:
  50727. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50728. switch (loopMode) {
  50729. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50730. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50731. return vec3Value;
  50732. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50733. return vec3Value.add(offsetValue.scale(repeatCount));
  50734. }
  50735. // Vector2
  50736. case Animation.ANIMATIONTYPE_VECTOR2:
  50737. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50738. switch (loopMode) {
  50739. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50740. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50741. return vec2Value;
  50742. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50743. return vec2Value.add(offsetValue.scale(repeatCount));
  50744. }
  50745. // Size
  50746. case Animation.ANIMATIONTYPE_SIZE:
  50747. switch (loopMode) {
  50748. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50749. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50750. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50751. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50752. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50753. }
  50754. // Color3
  50755. case Animation.ANIMATIONTYPE_COLOR3:
  50756. switch (loopMode) {
  50757. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50758. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50759. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50760. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50761. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50762. }
  50763. // Matrix
  50764. case Animation.ANIMATIONTYPE_MATRIX:
  50765. switch (loopMode) {
  50766. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50767. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50768. if (Animation.AllowMatricesInterpolation) {
  50769. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50770. }
  50771. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50772. return startValue;
  50773. }
  50774. default:
  50775. break;
  50776. }
  50777. break;
  50778. }
  50779. }
  50780. return this._getKeyValue(keys[keys.length - 1].value);
  50781. };
  50782. /**
  50783. * Defines the function to use to interpolate matrices
  50784. * @param startValue defines the start matrix
  50785. * @param endValue defines the end matrix
  50786. * @param gradient defines the gradient between both matrices
  50787. * @param result defines an optional target matrix where to store the interpolation
  50788. * @returns the interpolated matrix
  50789. */
  50790. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50791. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50792. if (result) {
  50793. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50794. return result;
  50795. }
  50796. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50797. }
  50798. if (result) {
  50799. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50800. return result;
  50801. }
  50802. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50803. };
  50804. /**
  50805. * Makes a copy of the animation
  50806. * @returns Cloned animation
  50807. */
  50808. Animation.prototype.clone = function () {
  50809. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50810. clone.enableBlending = this.enableBlending;
  50811. clone.blendingSpeed = this.blendingSpeed;
  50812. if (this._keys) {
  50813. clone.setKeys(this._keys);
  50814. }
  50815. if (this._ranges) {
  50816. clone._ranges = {};
  50817. for (var name in this._ranges) {
  50818. var range = this._ranges[name];
  50819. if (!range) {
  50820. continue;
  50821. }
  50822. clone._ranges[name] = range.clone();
  50823. }
  50824. }
  50825. return clone;
  50826. };
  50827. /**
  50828. * Sets the key frames of the animation
  50829. * @param values The animation key frames to set
  50830. */
  50831. Animation.prototype.setKeys = function (values) {
  50832. this._keys = values.slice(0);
  50833. };
  50834. /**
  50835. * Serializes the animation to an object
  50836. * @returns Serialized object
  50837. */
  50838. Animation.prototype.serialize = function () {
  50839. var serializationObject = {};
  50840. serializationObject.name = this.name;
  50841. serializationObject.property = this.targetProperty;
  50842. serializationObject.framePerSecond = this.framePerSecond;
  50843. serializationObject.dataType = this.dataType;
  50844. serializationObject.loopBehavior = this.loopMode;
  50845. serializationObject.enableBlending = this.enableBlending;
  50846. serializationObject.blendingSpeed = this.blendingSpeed;
  50847. var dataType = this.dataType;
  50848. serializationObject.keys = [];
  50849. var keys = this.getKeys();
  50850. for (var index = 0; index < keys.length; index++) {
  50851. var animationKey = keys[index];
  50852. var key = {};
  50853. key.frame = animationKey.frame;
  50854. switch (dataType) {
  50855. case Animation.ANIMATIONTYPE_FLOAT:
  50856. key.values = [animationKey.value];
  50857. break;
  50858. case Animation.ANIMATIONTYPE_QUATERNION:
  50859. case Animation.ANIMATIONTYPE_MATRIX:
  50860. case Animation.ANIMATIONTYPE_VECTOR3:
  50861. case Animation.ANIMATIONTYPE_COLOR3:
  50862. key.values = animationKey.value.asArray();
  50863. break;
  50864. }
  50865. serializationObject.keys.push(key);
  50866. }
  50867. serializationObject.ranges = [];
  50868. for (var name in this._ranges) {
  50869. var source = this._ranges[name];
  50870. if (!source) {
  50871. continue;
  50872. }
  50873. var range = {};
  50874. range.name = name;
  50875. range.from = source.from;
  50876. range.to = source.to;
  50877. serializationObject.ranges.push(range);
  50878. }
  50879. return serializationObject;
  50880. };
  50881. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50882. /**
  50883. * Get the float animation type
  50884. */
  50885. get: function () {
  50886. return Animation._ANIMATIONTYPE_FLOAT;
  50887. },
  50888. enumerable: true,
  50889. configurable: true
  50890. });
  50891. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50892. /**
  50893. * Get the Vector3 animation type
  50894. */
  50895. get: function () {
  50896. return Animation._ANIMATIONTYPE_VECTOR3;
  50897. },
  50898. enumerable: true,
  50899. configurable: true
  50900. });
  50901. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50902. /**
  50903. * Get the Vectpr2 animation type
  50904. */
  50905. get: function () {
  50906. return Animation._ANIMATIONTYPE_VECTOR2;
  50907. },
  50908. enumerable: true,
  50909. configurable: true
  50910. });
  50911. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50912. /**
  50913. * Get the Size animation type
  50914. */
  50915. get: function () {
  50916. return Animation._ANIMATIONTYPE_SIZE;
  50917. },
  50918. enumerable: true,
  50919. configurable: true
  50920. });
  50921. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50922. /**
  50923. * Get the Quaternion animation type
  50924. */
  50925. get: function () {
  50926. return Animation._ANIMATIONTYPE_QUATERNION;
  50927. },
  50928. enumerable: true,
  50929. configurable: true
  50930. });
  50931. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50932. /**
  50933. * Get the Matrix animation type
  50934. */
  50935. get: function () {
  50936. return Animation._ANIMATIONTYPE_MATRIX;
  50937. },
  50938. enumerable: true,
  50939. configurable: true
  50940. });
  50941. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50942. /**
  50943. * Get the Color3 animation type
  50944. */
  50945. get: function () {
  50946. return Animation._ANIMATIONTYPE_COLOR3;
  50947. },
  50948. enumerable: true,
  50949. configurable: true
  50950. });
  50951. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50952. /**
  50953. * Get the Relative Loop Mode
  50954. */
  50955. get: function () {
  50956. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50957. },
  50958. enumerable: true,
  50959. configurable: true
  50960. });
  50961. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50962. /**
  50963. * Get the Cycle Loop Mode
  50964. */
  50965. get: function () {
  50966. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50967. },
  50968. enumerable: true,
  50969. configurable: true
  50970. });
  50971. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50972. /**
  50973. * Get the Constant Loop Mode
  50974. */
  50975. get: function () {
  50976. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50977. },
  50978. enumerable: true,
  50979. configurable: true
  50980. });
  50981. /**
  50982. * Parses an animation object and creates an animation
  50983. * @param parsedAnimation Parsed animation object
  50984. * @returns Animation object
  50985. */
  50986. Animation.Parse = function (parsedAnimation) {
  50987. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50988. var dataType = parsedAnimation.dataType;
  50989. var keys = [];
  50990. var data;
  50991. var index;
  50992. if (parsedAnimation.enableBlending) {
  50993. animation.enableBlending = parsedAnimation.enableBlending;
  50994. }
  50995. if (parsedAnimation.blendingSpeed) {
  50996. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50997. }
  50998. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50999. var key = parsedAnimation.keys[index];
  51000. var inTangent;
  51001. var outTangent;
  51002. switch (dataType) {
  51003. case Animation.ANIMATIONTYPE_FLOAT:
  51004. data = key.values[0];
  51005. if (key.values.length >= 1) {
  51006. inTangent = key.values[1];
  51007. }
  51008. if (key.values.length >= 2) {
  51009. outTangent = key.values[2];
  51010. }
  51011. break;
  51012. case Animation.ANIMATIONTYPE_QUATERNION:
  51013. data = BABYLON.Quaternion.FromArray(key.values);
  51014. if (key.values.length >= 8) {
  51015. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51016. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51017. inTangent = _inTangent;
  51018. }
  51019. }
  51020. if (key.values.length >= 12) {
  51021. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51022. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51023. outTangent = _outTangent;
  51024. }
  51025. }
  51026. break;
  51027. case Animation.ANIMATIONTYPE_MATRIX:
  51028. data = BABYLON.Matrix.FromArray(key.values);
  51029. break;
  51030. case Animation.ANIMATIONTYPE_COLOR3:
  51031. data = BABYLON.Color3.FromArray(key.values);
  51032. break;
  51033. case Animation.ANIMATIONTYPE_VECTOR3:
  51034. default:
  51035. data = BABYLON.Vector3.FromArray(key.values);
  51036. break;
  51037. }
  51038. var keyData = {};
  51039. keyData.frame = key.frame;
  51040. keyData.value = data;
  51041. if (inTangent != undefined) {
  51042. keyData.inTangent = inTangent;
  51043. }
  51044. if (outTangent != undefined) {
  51045. keyData.outTangent = outTangent;
  51046. }
  51047. keys.push(keyData);
  51048. }
  51049. animation.setKeys(keys);
  51050. if (parsedAnimation.ranges) {
  51051. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51052. data = parsedAnimation.ranges[index];
  51053. animation.createRange(data.name, data.from, data.to);
  51054. }
  51055. }
  51056. return animation;
  51057. };
  51058. /**
  51059. * Appends the serialized animations from the source animations
  51060. * @param source Source containing the animations
  51061. * @param destination Target to store the animations
  51062. */
  51063. Animation.AppendSerializedAnimations = function (source, destination) {
  51064. if (source.animations) {
  51065. destination.animations = [];
  51066. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51067. var animation = source.animations[animationIndex];
  51068. destination.animations.push(animation.serialize());
  51069. }
  51070. }
  51071. };
  51072. /**
  51073. * Use matrix interpolation instead of using direct key value when animating matrices
  51074. */
  51075. Animation.AllowMatricesInterpolation = false;
  51076. /**
  51077. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51078. */
  51079. Animation.AllowMatrixDecomposeForInterpolation = true;
  51080. // Statics
  51081. /**
  51082. * Float animation type
  51083. */
  51084. Animation._ANIMATIONTYPE_FLOAT = 0;
  51085. /**
  51086. * Vector3 animation type
  51087. */
  51088. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51089. /**
  51090. * Quaternion animation type
  51091. */
  51092. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51093. /**
  51094. * Matrix animation type
  51095. */
  51096. Animation._ANIMATIONTYPE_MATRIX = 3;
  51097. /**
  51098. * Color3 animation type
  51099. */
  51100. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51101. /**
  51102. * Vector2 animation type
  51103. */
  51104. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51105. /**
  51106. * Size animation type
  51107. */
  51108. Animation._ANIMATIONTYPE_SIZE = 6;
  51109. /**
  51110. * Relative Loop Mode
  51111. */
  51112. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51113. /**
  51114. * Cycle Loop Mode
  51115. */
  51116. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51117. /**
  51118. * Constant Loop Mode
  51119. */
  51120. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51121. return Animation;
  51122. }());
  51123. BABYLON.Animation = Animation;
  51124. })(BABYLON || (BABYLON = {}));
  51125. //# sourceMappingURL=babylon.animation.js.map
  51126. var BABYLON;
  51127. (function (BABYLON) {
  51128. /**
  51129. * This class defines the direct association between an animation and a target
  51130. */
  51131. var TargetedAnimation = /** @class */ (function () {
  51132. function TargetedAnimation() {
  51133. }
  51134. return TargetedAnimation;
  51135. }());
  51136. BABYLON.TargetedAnimation = TargetedAnimation;
  51137. /**
  51138. * Use this class to create coordinated animations on multiple targets
  51139. */
  51140. var AnimationGroup = /** @class */ (function () {
  51141. function AnimationGroup(name, scene) {
  51142. if (scene === void 0) { scene = null; }
  51143. this.name = name;
  51144. this._targetedAnimations = new Array();
  51145. this._animatables = new Array();
  51146. this._from = Number.MAX_VALUE;
  51147. this._to = -Number.MAX_VALUE;
  51148. this._speedRatio = 1;
  51149. this.onAnimationEndObservable = new BABYLON.Observable();
  51150. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51151. this._scene.animationGroups.push(this);
  51152. }
  51153. Object.defineProperty(AnimationGroup.prototype, "from", {
  51154. /**
  51155. * Gets the first frame
  51156. */
  51157. get: function () {
  51158. return this._from;
  51159. },
  51160. enumerable: true,
  51161. configurable: true
  51162. });
  51163. Object.defineProperty(AnimationGroup.prototype, "to", {
  51164. /**
  51165. * Gets the last frame
  51166. */
  51167. get: function () {
  51168. return this._to;
  51169. },
  51170. enumerable: true,
  51171. configurable: true
  51172. });
  51173. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51174. /**
  51175. * Define if the animations are started
  51176. */
  51177. get: function () {
  51178. return this._isStarted;
  51179. },
  51180. enumerable: true,
  51181. configurable: true
  51182. });
  51183. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51184. /**
  51185. * Gets or sets the speed ratio to use for all animations
  51186. */
  51187. get: function () {
  51188. return this._speedRatio;
  51189. },
  51190. /**
  51191. * Gets or sets the speed ratio to use for all animations
  51192. */
  51193. set: function (value) {
  51194. if (this._speedRatio === value) {
  51195. return;
  51196. }
  51197. this._speedRatio = value;
  51198. for (var index = 0; index < this._animatables.length; index++) {
  51199. var animatable = this._animatables[index];
  51200. animatable.speedRatio = this._speedRatio;
  51201. }
  51202. },
  51203. enumerable: true,
  51204. configurable: true
  51205. });
  51206. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51207. /**
  51208. * Gets the targeted animations for this animation group
  51209. */
  51210. get: function () {
  51211. return this._targetedAnimations;
  51212. },
  51213. enumerable: true,
  51214. configurable: true
  51215. });
  51216. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51217. /**
  51218. * returning the list of animatables controlled by this animation group.
  51219. */
  51220. get: function () {
  51221. return this._animatables;
  51222. },
  51223. enumerable: true,
  51224. configurable: true
  51225. });
  51226. /**
  51227. * Add an animation (with its target) in the group
  51228. * @param animation defines the animation we want to add
  51229. * @param target defines the target of the animation
  51230. * @returns the {BABYLON.TargetedAnimation} object
  51231. */
  51232. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51233. var targetedAnimation = {
  51234. animation: animation,
  51235. target: target
  51236. };
  51237. var keys = animation.getKeys();
  51238. if (this._from > keys[0].frame) {
  51239. this._from = keys[0].frame;
  51240. }
  51241. if (this._to < keys[keys.length - 1].frame) {
  51242. this._to = keys[keys.length - 1].frame;
  51243. }
  51244. this._targetedAnimations.push(targetedAnimation);
  51245. return targetedAnimation;
  51246. };
  51247. /**
  51248. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51249. * It can add constant keys at begin or end
  51250. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to 0)
  51251. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51252. */
  51253. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51254. if (beginFrame === void 0) { beginFrame = 0; }
  51255. if (endFrame === void 0) { endFrame = null; }
  51256. if (beginFrame == null)
  51257. beginFrame = this._from;
  51258. if (endFrame == null)
  51259. endFrame = this._to;
  51260. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51261. var targetedAnimation = this._targetedAnimations[index];
  51262. var keys = targetedAnimation.animation.getKeys();
  51263. var startKey = keys[0];
  51264. var endKey = keys[keys.length - 1];
  51265. if (startKey.frame > beginFrame) {
  51266. var newKey = {
  51267. frame: beginFrame,
  51268. value: startKey.value,
  51269. inTangent: startKey.inTangent,
  51270. outTangent: startKey.outTangent,
  51271. interpolation: startKey.interpolation
  51272. };
  51273. keys.splice(0, 0, newKey);
  51274. }
  51275. if (endKey.frame < endFrame) {
  51276. var newKey = {
  51277. frame: endFrame,
  51278. value: endKey.value,
  51279. inTangent: endKey.outTangent,
  51280. outTangent: endKey.outTangent,
  51281. interpolation: endKey.interpolation
  51282. };
  51283. keys.push(newKey);
  51284. }
  51285. }
  51286. this._from = beginFrame;
  51287. this._to = endFrame;
  51288. return this;
  51289. };
  51290. /**
  51291. * Start all animations on given targets
  51292. * @param loop defines if animations must loop
  51293. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51294. * @param from defines the from key (optional)
  51295. * @param to defines the to key (optional)
  51296. * @returns the current animation group
  51297. */
  51298. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51299. var _this = this;
  51300. if (loop === void 0) { loop = false; }
  51301. if (speedRatio === void 0) { speedRatio = 1; }
  51302. if (this._isStarted || this._targetedAnimations.length === 0) {
  51303. return this;
  51304. }
  51305. var _loop_1 = function (targetedAnimation) {
  51306. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51307. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51308. }));
  51309. };
  51310. var this_1 = this;
  51311. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51312. var targetedAnimation = _a[_i];
  51313. _loop_1(targetedAnimation);
  51314. }
  51315. this._speedRatio = speedRatio;
  51316. this._isStarted = true;
  51317. return this;
  51318. };
  51319. /**
  51320. * Pause all animations
  51321. */
  51322. AnimationGroup.prototype.pause = function () {
  51323. if (!this._isStarted) {
  51324. return this;
  51325. }
  51326. for (var index = 0; index < this._animatables.length; index++) {
  51327. var animatable = this._animatables[index];
  51328. animatable.pause();
  51329. }
  51330. return this;
  51331. };
  51332. /**
  51333. * Play all animations to initial state
  51334. * This function will start() the animations if they were not started or will restart() them if they were paused
  51335. * @param loop defines if animations must loop
  51336. */
  51337. AnimationGroup.prototype.play = function (loop) {
  51338. if (this.isStarted) {
  51339. if (loop !== undefined) {
  51340. for (var index = 0; index < this._animatables.length; index++) {
  51341. var animatable = this._animatables[index];
  51342. animatable.loopAnimation = loop;
  51343. }
  51344. }
  51345. this.restart();
  51346. }
  51347. else {
  51348. this.start(loop, this._speedRatio);
  51349. }
  51350. return this;
  51351. };
  51352. /**
  51353. * Reset all animations to initial state
  51354. */
  51355. AnimationGroup.prototype.reset = function () {
  51356. if (!this._isStarted) {
  51357. return this;
  51358. }
  51359. for (var index = 0; index < this._animatables.length; index++) {
  51360. var animatable = this._animatables[index];
  51361. animatable.reset();
  51362. }
  51363. return this;
  51364. };
  51365. /**
  51366. * Restart animations from key 0
  51367. */
  51368. AnimationGroup.prototype.restart = function () {
  51369. if (!this._isStarted) {
  51370. return this;
  51371. }
  51372. for (var index = 0; index < this._animatables.length; index++) {
  51373. var animatable = this._animatables[index];
  51374. animatable.restart();
  51375. }
  51376. return this;
  51377. };
  51378. /**
  51379. * Stop all animations
  51380. */
  51381. AnimationGroup.prototype.stop = function () {
  51382. if (!this._isStarted) {
  51383. return this;
  51384. }
  51385. for (var index = 0; index < this._animatables.length; index++) {
  51386. var animatable = this._animatables[index];
  51387. animatable.stop();
  51388. }
  51389. this._isStarted = false;
  51390. return this;
  51391. };
  51392. /**
  51393. * Set animation weight for all animatables
  51394. * @param weight defines the weight to use
  51395. * @return the animationGroup
  51396. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51397. */
  51398. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51399. for (var index = 0; index < this._animatables.length; index++) {
  51400. var animatable = this._animatables[index];
  51401. animatable.weight = weight;
  51402. }
  51403. return this;
  51404. };
  51405. /**
  51406. * Synchronize and normalize all animatables with a source animatable
  51407. * @param root defines the root animatable to synchronize with
  51408. * @return the animationGroup
  51409. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51410. */
  51411. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51412. for (var index = 0; index < this._animatables.length; index++) {
  51413. var animatable = this._animatables[index];
  51414. animatable.syncWith(root);
  51415. }
  51416. return this;
  51417. };
  51418. /**
  51419. * Goes to a specific frame in this animation group
  51420. * @param frame the frame number to go to
  51421. * @return the animationGroup
  51422. */
  51423. AnimationGroup.prototype.goToFrame = function (frame) {
  51424. if (!this._isStarted) {
  51425. return this;
  51426. }
  51427. for (var index = 0; index < this._animatables.length; index++) {
  51428. var animatable = this._animatables[index];
  51429. animatable.goToFrame(frame);
  51430. }
  51431. return this;
  51432. };
  51433. /**
  51434. * Dispose all associated resources
  51435. */
  51436. AnimationGroup.prototype.dispose = function () {
  51437. this._targetedAnimations = [];
  51438. this._animatables = [];
  51439. var index = this._scene.animationGroups.indexOf(this);
  51440. if (index > -1) {
  51441. this._scene.animationGroups.splice(index, 1);
  51442. }
  51443. };
  51444. return AnimationGroup;
  51445. }());
  51446. BABYLON.AnimationGroup = AnimationGroup;
  51447. })(BABYLON || (BABYLON = {}));
  51448. //# sourceMappingURL=babylon.animationGroup.js.map
  51449. var BABYLON;
  51450. (function (BABYLON) {
  51451. /**
  51452. * Defines a runtime animation
  51453. */
  51454. var RuntimeAnimation = /** @class */ (function () {
  51455. /**
  51456. * Create a new RuntimeAnimation object
  51457. * @param target defines the target of the animation
  51458. * @param animation defines the source animation object
  51459. * @param scene defines the hosting scene
  51460. * @param host defines the initiating Animatable
  51461. */
  51462. function RuntimeAnimation(target, animation, scene, host) {
  51463. /**
  51464. * The current frame of the runtime animation
  51465. */
  51466. this._currentFrame = 0;
  51467. /**
  51468. * The offsets cache of the runtime animation
  51469. */
  51470. this._offsetsCache = {};
  51471. /**
  51472. * The high limits cache of the runtime animation
  51473. */
  51474. this._highLimitsCache = {};
  51475. /**
  51476. * Specifies if the runtime animation has been stopped
  51477. */
  51478. this._stopped = false;
  51479. /**
  51480. * The blending factor of the runtime animation
  51481. */
  51482. this._blendingFactor = 0;
  51483. /**
  51484. * The target path of the runtime animation
  51485. */
  51486. this._targetPath = "";
  51487. /**
  51488. * The weight of the runtime animation
  51489. */
  51490. this._weight = 1.0;
  51491. /**
  51492. * The ratio offset of the runtime animation
  51493. */
  51494. this._ratioOffset = 0;
  51495. /**
  51496. * The previous delay of the runtime animation
  51497. */
  51498. this._previousDelay = 0;
  51499. /**
  51500. * The previous ratio of the runtime animation
  51501. */
  51502. this._previousRatio = 0;
  51503. this._animation = animation;
  51504. this._target = target;
  51505. this._scene = scene;
  51506. this._host = host;
  51507. animation._runtimeAnimations.push(this);
  51508. }
  51509. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51510. /**
  51511. * Gets the current frame of the runtime animation
  51512. */
  51513. get: function () {
  51514. return this._currentFrame;
  51515. },
  51516. enumerable: true,
  51517. configurable: true
  51518. });
  51519. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51520. /**
  51521. * Gets the weight of the runtime animation
  51522. */
  51523. get: function () {
  51524. return this._weight;
  51525. },
  51526. enumerable: true,
  51527. configurable: true
  51528. });
  51529. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51530. /**
  51531. * Gets the original value of the runtime animation
  51532. */
  51533. get: function () {
  51534. return this._originalValue;
  51535. },
  51536. enumerable: true,
  51537. configurable: true
  51538. });
  51539. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51540. /**
  51541. * Gets the current value of the runtime animation
  51542. */
  51543. get: function () {
  51544. return this._currentValue;
  51545. },
  51546. enumerable: true,
  51547. configurable: true
  51548. });
  51549. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51550. /**
  51551. * Gets the target path of the runtime animation
  51552. */
  51553. get: function () {
  51554. return this._targetPath;
  51555. },
  51556. enumerable: true,
  51557. configurable: true
  51558. });
  51559. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51560. /**
  51561. * Gets the actual target of the runtime animation
  51562. */
  51563. get: function () {
  51564. return this._activeTarget;
  51565. },
  51566. enumerable: true,
  51567. configurable: true
  51568. });
  51569. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51570. /**
  51571. * Gets the animation from the runtime animation
  51572. */
  51573. get: function () {
  51574. return this._animation;
  51575. },
  51576. enumerable: true,
  51577. configurable: true
  51578. });
  51579. /**
  51580. * Resets the runtime animation to the beginning
  51581. * @param restoreOriginal defines whether to restore the target property to the original value
  51582. */
  51583. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51584. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51585. if (restoreOriginal && this._originalValue != null) {
  51586. this.setValue(this._originalValue, -1);
  51587. }
  51588. this._offsetsCache = {};
  51589. this._highLimitsCache = {};
  51590. this._currentFrame = 0;
  51591. this._blendingFactor = 0;
  51592. this._originalValue = null;
  51593. };
  51594. /**
  51595. * Specifies if the runtime animation is stopped
  51596. * @returns Boolean specifying if the runtime animation is stopped
  51597. */
  51598. RuntimeAnimation.prototype.isStopped = function () {
  51599. return this._stopped;
  51600. };
  51601. /**
  51602. * Disposes of the runtime animation
  51603. */
  51604. RuntimeAnimation.prototype.dispose = function () {
  51605. var index = this._animation.runtimeAnimations.indexOf(this);
  51606. if (index > -1) {
  51607. this._animation.runtimeAnimations.splice(index, 1);
  51608. }
  51609. };
  51610. /**
  51611. * Interpolates the animation from the current frame
  51612. * @param currentFrame The frame to interpolate the animation to
  51613. * @param repeatCount The number of times that the animation should loop
  51614. * @param loopMode The type of looping mode to use
  51615. * @param offsetValue Animation offset value
  51616. * @param highLimitValue The high limit value
  51617. * @returns The interpolated value
  51618. */
  51619. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51620. this._currentFrame = currentFrame;
  51621. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51622. this._workValue = BABYLON.Matrix.Zero();
  51623. }
  51624. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51625. };
  51626. /**
  51627. * Apply the interpolated value to the target
  51628. * @param currentValue defines the value computed by the animation
  51629. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51630. */
  51631. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51632. if (weight === void 0) { weight = 1.0; }
  51633. if (this._target instanceof Array) {
  51634. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51635. var target = _a[_i];
  51636. this._setValue(target, currentValue, weight);
  51637. }
  51638. }
  51639. else {
  51640. this._setValue(this._target, currentValue, weight);
  51641. }
  51642. };
  51643. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51644. // Set value
  51645. var path;
  51646. var destination;
  51647. var targetPropertyPath = this._animation.targetPropertyPath;
  51648. if (targetPropertyPath.length > 1) {
  51649. var property = target[targetPropertyPath[0]];
  51650. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51651. property = property[targetPropertyPath[index]];
  51652. }
  51653. path = targetPropertyPath[targetPropertyPath.length - 1];
  51654. destination = property;
  51655. }
  51656. else {
  51657. path = targetPropertyPath[0];
  51658. destination = target;
  51659. }
  51660. this._targetPath = path;
  51661. this._activeTarget = destination;
  51662. this._weight = weight;
  51663. if (!this._originalValue) {
  51664. var originalValue = void 0;
  51665. if (destination.getRestPose && path === "_matrix") { // For bones
  51666. originalValue = destination.getRestPose();
  51667. }
  51668. else {
  51669. originalValue = destination[path];
  51670. }
  51671. if (originalValue && originalValue.clone) {
  51672. this._originalValue = originalValue.clone();
  51673. }
  51674. else {
  51675. this._originalValue = originalValue;
  51676. }
  51677. }
  51678. // Blending
  51679. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51680. if (enableBlending && this._blendingFactor <= 1.0) {
  51681. if (!this._originalBlendValue) {
  51682. var originalValue = destination[path];
  51683. if (originalValue.clone) {
  51684. this._originalBlendValue = originalValue.clone();
  51685. }
  51686. else {
  51687. this._originalBlendValue = originalValue;
  51688. }
  51689. }
  51690. if (this._originalBlendValue.m) { // Matrix
  51691. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51692. if (this._currentValue) {
  51693. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51694. }
  51695. else {
  51696. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51697. }
  51698. }
  51699. else {
  51700. if (this._currentValue) {
  51701. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51702. }
  51703. else {
  51704. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51705. }
  51706. }
  51707. }
  51708. else {
  51709. var constructor = this._originalBlendValue.constructor;
  51710. if (constructor.Lerp) { // Lerp supported
  51711. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51712. }
  51713. else if (constructor.Slerp) { // Slerp supported
  51714. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51715. }
  51716. else if (this._originalBlendValue.toFixed) { // Number
  51717. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51718. }
  51719. else { // Blending not supported
  51720. this._currentValue = currentValue;
  51721. }
  51722. }
  51723. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51724. this._blendingFactor += blendingSpeed;
  51725. }
  51726. else {
  51727. this._currentValue = currentValue;
  51728. }
  51729. if (weight !== -1.0) {
  51730. this._scene._registerTargetForLateAnimationBinding(this);
  51731. }
  51732. else {
  51733. destination[path] = this._currentValue;
  51734. }
  51735. if (target.markAsDirty) {
  51736. target.markAsDirty(this._animation.targetProperty);
  51737. }
  51738. };
  51739. /**
  51740. * Gets the loop pmode of the runtime animation
  51741. * @returns Loop Mode
  51742. */
  51743. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51744. if (this._target && this._target.animationPropertiesOverride) {
  51745. return this._target.animationPropertiesOverride.loopMode;
  51746. }
  51747. return this._animation.loopMode;
  51748. };
  51749. /**
  51750. * Move the current animation to a given frame
  51751. * @param frame defines the frame to move to
  51752. */
  51753. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51754. var keys = this._animation.getKeys();
  51755. if (frame < keys[0].frame) {
  51756. frame = keys[0].frame;
  51757. }
  51758. else if (frame > keys[keys.length - 1].frame) {
  51759. frame = keys[keys.length - 1].frame;
  51760. }
  51761. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51762. this.setValue(currentValue, -1);
  51763. };
  51764. /**
  51765. * @hidden Internal use only
  51766. */
  51767. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51768. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51769. this._ratioOffset = this._previousRatio - newRatio;
  51770. };
  51771. /**
  51772. * Execute the current animation
  51773. * @param delay defines the delay to add to the current frame
  51774. * @param from defines the lower bound of the animation range
  51775. * @param to defines the upper bound of the animation range
  51776. * @param loop defines if the current animation must loop
  51777. * @param speedRatio defines the current speed ratio
  51778. * @param weight defines the weight of the animation (default is -1 so no weight)
  51779. * @returns a boolean indicating if the animation has ended
  51780. */
  51781. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51782. if (weight === void 0) { weight = -1.0; }
  51783. var targetPropertyPath = this._animation.targetPropertyPath;
  51784. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51785. this._stopped = true;
  51786. return false;
  51787. }
  51788. var returnValue = true;
  51789. var keys = this._animation.getKeys();
  51790. // Adding a start key at frame 0 if missing
  51791. if (keys[0].frame !== 0) {
  51792. var newKey = { frame: 0, value: keys[0].value };
  51793. keys.splice(0, 0, newKey);
  51794. }
  51795. // Check limits
  51796. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51797. from = keys[0].frame;
  51798. }
  51799. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51800. to = keys[keys.length - 1].frame;
  51801. }
  51802. //to and from cannot be the same key
  51803. if (from === to) {
  51804. if (from > keys[0].frame) {
  51805. from--;
  51806. }
  51807. else if (to < keys[keys.length - 1].frame) {
  51808. to++;
  51809. }
  51810. }
  51811. // Compute ratio
  51812. var range = to - from;
  51813. var offsetValue;
  51814. // ratio represents the frame delta between from and to
  51815. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51816. var highLimitValue = 0;
  51817. this._previousDelay = delay;
  51818. this._previousRatio = ratio;
  51819. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51820. returnValue = false;
  51821. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51822. }
  51823. else {
  51824. // Get max value if required
  51825. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51826. var keyOffset = to.toString() + from.toString();
  51827. if (!this._offsetsCache[keyOffset]) {
  51828. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51829. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51830. switch (this._animation.dataType) {
  51831. // Float
  51832. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51833. this._offsetsCache[keyOffset] = toValue - fromValue;
  51834. break;
  51835. // Quaternion
  51836. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51837. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51838. break;
  51839. // Vector3
  51840. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51841. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51842. // Vector2
  51843. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51844. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51845. // Size
  51846. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51847. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51848. // Color3
  51849. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51850. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51851. default:
  51852. break;
  51853. }
  51854. this._highLimitsCache[keyOffset] = toValue;
  51855. }
  51856. highLimitValue = this._highLimitsCache[keyOffset];
  51857. offsetValue = this._offsetsCache[keyOffset];
  51858. }
  51859. }
  51860. if (offsetValue === undefined) {
  51861. switch (this._animation.dataType) {
  51862. // Float
  51863. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51864. offsetValue = 0;
  51865. break;
  51866. // Quaternion
  51867. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51868. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51869. break;
  51870. // Vector3
  51871. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51872. offsetValue = BABYLON.Vector3.Zero();
  51873. break;
  51874. // Vector2
  51875. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51876. offsetValue = BABYLON.Vector2.Zero();
  51877. break;
  51878. // Size
  51879. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51880. offsetValue = BABYLON.Size.Zero();
  51881. break;
  51882. // Color3
  51883. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51884. offsetValue = BABYLON.Color3.Black();
  51885. }
  51886. }
  51887. // Compute value
  51888. var repeatCount = (ratio / range) >> 0;
  51889. var currentFrame = returnValue ? from + ratio % range : to;
  51890. // Need to normalize?
  51891. if (this._host && this._host.syncRoot) {
  51892. var syncRoot = this._host.syncRoot;
  51893. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51894. currentFrame = from + (to - from) * hostNormalizedFrame;
  51895. }
  51896. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51897. // Set value
  51898. this.setValue(currentValue, weight);
  51899. // Check events
  51900. var events = this._animation.getEvents();
  51901. for (var index = 0; index < events.length; index++) {
  51902. // Make sure current frame has passed event frame and that event frame is within the current range
  51903. // Also, handle both forward and reverse animations
  51904. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51905. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51906. var event = events[index];
  51907. if (!event.isDone) {
  51908. // If event should be done only once, remove it.
  51909. if (event.onlyOnce) {
  51910. events.splice(index, 1);
  51911. index--;
  51912. }
  51913. event.isDone = true;
  51914. event.action();
  51915. } // Don't do anything if the event has already be done.
  51916. }
  51917. else if (events[index].isDone && !events[index].onlyOnce) {
  51918. // reset event, the animation is looping
  51919. events[index].isDone = false;
  51920. }
  51921. }
  51922. if (!returnValue) {
  51923. this._stopped = true;
  51924. }
  51925. return returnValue;
  51926. };
  51927. return RuntimeAnimation;
  51928. }());
  51929. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51930. })(BABYLON || (BABYLON = {}));
  51931. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51932. var BABYLON;
  51933. (function (BABYLON) {
  51934. var Animatable = /** @class */ (function () {
  51935. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51936. if (fromFrame === void 0) { fromFrame = 0; }
  51937. if (toFrame === void 0) { toFrame = 100; }
  51938. if (loopAnimation === void 0) { loopAnimation = false; }
  51939. if (speedRatio === void 0) { speedRatio = 1.0; }
  51940. this.target = target;
  51941. this.fromFrame = fromFrame;
  51942. this.toFrame = toFrame;
  51943. this.loopAnimation = loopAnimation;
  51944. this.onAnimationEnd = onAnimationEnd;
  51945. this._localDelayOffset = null;
  51946. this._pausedDelay = null;
  51947. this._runtimeAnimations = new Array();
  51948. this._paused = false;
  51949. this._speedRatio = 1;
  51950. this._weight = -1.0;
  51951. this.animationStarted = false;
  51952. this._scene = scene;
  51953. if (animations) {
  51954. this.appendAnimations(target, animations);
  51955. }
  51956. this._speedRatio = speedRatio;
  51957. scene._activeAnimatables.push(this);
  51958. }
  51959. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51960. /**
  51961. * Gets the root Animatable used to synchronize and normalize animations
  51962. */
  51963. get: function () {
  51964. return this._syncRoot;
  51965. },
  51966. enumerable: true,
  51967. configurable: true
  51968. });
  51969. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51970. /**
  51971. * Gets the current frame of the first RuntimeAnimation
  51972. * Used to synchronize Animatables
  51973. */
  51974. get: function () {
  51975. if (this._runtimeAnimations.length === 0) {
  51976. return 0;
  51977. }
  51978. return this._runtimeAnimations[0].currentFrame;
  51979. },
  51980. enumerable: true,
  51981. configurable: true
  51982. });
  51983. Object.defineProperty(Animatable.prototype, "weight", {
  51984. /**
  51985. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51986. */
  51987. get: function () {
  51988. return this._weight;
  51989. },
  51990. set: function (value) {
  51991. if (value === -1) { // -1 is ok and means no weight
  51992. this._weight = -1;
  51993. return;
  51994. }
  51995. // Else weight must be in [0, 1] range
  51996. this._weight = Math.min(Math.max(value, 0), 1.0);
  51997. },
  51998. enumerable: true,
  51999. configurable: true
  52000. });
  52001. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52002. /**
  52003. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52004. */
  52005. get: function () {
  52006. return this._speedRatio;
  52007. },
  52008. set: function (value) {
  52009. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52010. var animation = this._runtimeAnimations[index];
  52011. animation._prepareForSpeedRatioChange(value);
  52012. }
  52013. this._speedRatio = value;
  52014. },
  52015. enumerable: true,
  52016. configurable: true
  52017. });
  52018. // Methods
  52019. /**
  52020. * Synchronize and normalize current Animatable with a source Animatable
  52021. * This is useful when using animation weights and when animations are not of the same length
  52022. * @param root defines the root Animatable to synchronize with
  52023. * @returns the current Animatable
  52024. */
  52025. Animatable.prototype.syncWith = function (root) {
  52026. this._syncRoot = root;
  52027. if (root) {
  52028. // Make sure this animatable will animate after the root
  52029. var index = this._scene._activeAnimatables.indexOf(this);
  52030. if (index > -1) {
  52031. this._scene._activeAnimatables.splice(index, 1);
  52032. this._scene._activeAnimatables.push(this);
  52033. }
  52034. }
  52035. return this;
  52036. };
  52037. Animatable.prototype.getAnimations = function () {
  52038. return this._runtimeAnimations;
  52039. };
  52040. Animatable.prototype.appendAnimations = function (target, animations) {
  52041. for (var index = 0; index < animations.length; index++) {
  52042. var animation = animations[index];
  52043. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52044. }
  52045. };
  52046. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52047. var runtimeAnimations = this._runtimeAnimations;
  52048. for (var index = 0; index < runtimeAnimations.length; index++) {
  52049. if (runtimeAnimations[index].animation.targetProperty === property) {
  52050. return runtimeAnimations[index].animation;
  52051. }
  52052. }
  52053. return null;
  52054. };
  52055. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52056. var runtimeAnimations = this._runtimeAnimations;
  52057. for (var index = 0; index < runtimeAnimations.length; index++) {
  52058. if (runtimeAnimations[index].animation.targetProperty === property) {
  52059. return runtimeAnimations[index];
  52060. }
  52061. }
  52062. return null;
  52063. };
  52064. Animatable.prototype.reset = function () {
  52065. var runtimeAnimations = this._runtimeAnimations;
  52066. for (var index = 0; index < runtimeAnimations.length; index++) {
  52067. runtimeAnimations[index].reset(true);
  52068. }
  52069. this._localDelayOffset = null;
  52070. this._pausedDelay = null;
  52071. };
  52072. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52073. var runtimeAnimations = this._runtimeAnimations;
  52074. for (var index = 0; index < runtimeAnimations.length; index++) {
  52075. runtimeAnimations[index].animation.enableBlending = true;
  52076. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52077. }
  52078. };
  52079. Animatable.prototype.disableBlending = function () {
  52080. var runtimeAnimations = this._runtimeAnimations;
  52081. for (var index = 0; index < runtimeAnimations.length; index++) {
  52082. runtimeAnimations[index].animation.enableBlending = false;
  52083. }
  52084. };
  52085. Animatable.prototype.goToFrame = function (frame) {
  52086. var runtimeAnimations = this._runtimeAnimations;
  52087. if (runtimeAnimations[0]) {
  52088. var fps = runtimeAnimations[0].animation.framePerSecond;
  52089. var currentFrame = runtimeAnimations[0].currentFrame;
  52090. var adjustTime = frame - currentFrame;
  52091. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52092. if (this._localDelayOffset === null) {
  52093. this._localDelayOffset = 0;
  52094. }
  52095. this._localDelayOffset -= delay;
  52096. }
  52097. for (var index = 0; index < runtimeAnimations.length; index++) {
  52098. runtimeAnimations[index].goToFrame(frame);
  52099. }
  52100. };
  52101. Animatable.prototype.pause = function () {
  52102. if (this._paused) {
  52103. return;
  52104. }
  52105. this._paused = true;
  52106. };
  52107. Animatable.prototype.restart = function () {
  52108. this._paused = false;
  52109. };
  52110. Animatable.prototype.stop = function (animationName) {
  52111. if (animationName) {
  52112. var idx = this._scene._activeAnimatables.indexOf(this);
  52113. if (idx > -1) {
  52114. var runtimeAnimations = this._runtimeAnimations;
  52115. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52116. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52117. continue;
  52118. }
  52119. runtimeAnimations[index].dispose();
  52120. runtimeAnimations.splice(index, 1);
  52121. }
  52122. if (runtimeAnimations.length == 0) {
  52123. this._scene._activeAnimatables.splice(idx, 1);
  52124. if (this.onAnimationEnd) {
  52125. this.onAnimationEnd();
  52126. }
  52127. }
  52128. }
  52129. }
  52130. else {
  52131. var index = this._scene._activeAnimatables.indexOf(this);
  52132. if (index > -1) {
  52133. this._scene._activeAnimatables.splice(index, 1);
  52134. var runtimeAnimations = this._runtimeAnimations;
  52135. for (var index = 0; index < runtimeAnimations.length; index++) {
  52136. runtimeAnimations[index].dispose();
  52137. }
  52138. if (this.onAnimationEnd) {
  52139. this.onAnimationEnd();
  52140. }
  52141. }
  52142. }
  52143. };
  52144. Animatable.prototype._animate = function (delay) {
  52145. if (this._paused) {
  52146. this.animationStarted = false;
  52147. if (this._pausedDelay === null) {
  52148. this._pausedDelay = delay;
  52149. }
  52150. return true;
  52151. }
  52152. if (this._localDelayOffset === null) {
  52153. this._localDelayOffset = delay;
  52154. this._pausedDelay = null;
  52155. }
  52156. else if (this._pausedDelay !== null) {
  52157. this._localDelayOffset += delay - this._pausedDelay;
  52158. this._pausedDelay = null;
  52159. }
  52160. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52161. return true;
  52162. }
  52163. // Animating
  52164. var running = false;
  52165. var runtimeAnimations = this._runtimeAnimations;
  52166. var index;
  52167. for (index = 0; index < runtimeAnimations.length; index++) {
  52168. var animation = runtimeAnimations[index];
  52169. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52170. running = running || isRunning;
  52171. }
  52172. this.animationStarted = running;
  52173. if (!running) {
  52174. // Remove from active animatables
  52175. index = this._scene._activeAnimatables.indexOf(this);
  52176. this._scene._activeAnimatables.splice(index, 1);
  52177. // Dispose all runtime animations
  52178. for (index = 0; index < runtimeAnimations.length; index++) {
  52179. runtimeAnimations[index].dispose();
  52180. }
  52181. }
  52182. if (!running && this.onAnimationEnd) {
  52183. this.onAnimationEnd();
  52184. this.onAnimationEnd = null;
  52185. }
  52186. return running;
  52187. };
  52188. return Animatable;
  52189. }());
  52190. BABYLON.Animatable = Animatable;
  52191. })(BABYLON || (BABYLON = {}));
  52192. //# sourceMappingURL=babylon.animatable.js.map
  52193. var BABYLON;
  52194. (function (BABYLON) {
  52195. var EasingFunction = /** @class */ (function () {
  52196. function EasingFunction() {
  52197. // Properties
  52198. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52199. }
  52200. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52201. get: function () {
  52202. return EasingFunction._EASINGMODE_EASEIN;
  52203. },
  52204. enumerable: true,
  52205. configurable: true
  52206. });
  52207. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52208. get: function () {
  52209. return EasingFunction._EASINGMODE_EASEOUT;
  52210. },
  52211. enumerable: true,
  52212. configurable: true
  52213. });
  52214. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52215. get: function () {
  52216. return EasingFunction._EASINGMODE_EASEINOUT;
  52217. },
  52218. enumerable: true,
  52219. configurable: true
  52220. });
  52221. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52222. var n = Math.min(Math.max(easingMode, 0), 2);
  52223. this._easingMode = n;
  52224. };
  52225. EasingFunction.prototype.getEasingMode = function () {
  52226. return this._easingMode;
  52227. };
  52228. EasingFunction.prototype.easeInCore = function (gradient) {
  52229. throw new Error('You must implement this method');
  52230. };
  52231. EasingFunction.prototype.ease = function (gradient) {
  52232. switch (this._easingMode) {
  52233. case EasingFunction.EASINGMODE_EASEIN:
  52234. return this.easeInCore(gradient);
  52235. case EasingFunction.EASINGMODE_EASEOUT:
  52236. return (1 - this.easeInCore(1 - gradient));
  52237. }
  52238. if (gradient >= 0.5) {
  52239. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52240. }
  52241. return (this.easeInCore(gradient * 2) * 0.5);
  52242. };
  52243. //Statics
  52244. EasingFunction._EASINGMODE_EASEIN = 0;
  52245. EasingFunction._EASINGMODE_EASEOUT = 1;
  52246. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52247. return EasingFunction;
  52248. }());
  52249. BABYLON.EasingFunction = EasingFunction;
  52250. var CircleEase = /** @class */ (function (_super) {
  52251. __extends(CircleEase, _super);
  52252. function CircleEase() {
  52253. return _super !== null && _super.apply(this, arguments) || this;
  52254. }
  52255. CircleEase.prototype.easeInCore = function (gradient) {
  52256. gradient = Math.max(0, Math.min(1, gradient));
  52257. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52258. };
  52259. return CircleEase;
  52260. }(EasingFunction));
  52261. BABYLON.CircleEase = CircleEase;
  52262. var BackEase = /** @class */ (function (_super) {
  52263. __extends(BackEase, _super);
  52264. function BackEase(amplitude) {
  52265. if (amplitude === void 0) { amplitude = 1; }
  52266. var _this = _super.call(this) || this;
  52267. _this.amplitude = amplitude;
  52268. return _this;
  52269. }
  52270. BackEase.prototype.easeInCore = function (gradient) {
  52271. var num = Math.max(0, this.amplitude);
  52272. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52273. };
  52274. return BackEase;
  52275. }(EasingFunction));
  52276. BABYLON.BackEase = BackEase;
  52277. var BounceEase = /** @class */ (function (_super) {
  52278. __extends(BounceEase, _super);
  52279. function BounceEase(bounces, bounciness) {
  52280. if (bounces === void 0) { bounces = 3; }
  52281. if (bounciness === void 0) { bounciness = 2; }
  52282. var _this = _super.call(this) || this;
  52283. _this.bounces = bounces;
  52284. _this.bounciness = bounciness;
  52285. return _this;
  52286. }
  52287. BounceEase.prototype.easeInCore = function (gradient) {
  52288. var y = Math.max(0.0, this.bounces);
  52289. var bounciness = this.bounciness;
  52290. if (bounciness <= 1.0) {
  52291. bounciness = 1.001;
  52292. }
  52293. var num9 = Math.pow(bounciness, y);
  52294. var num5 = 1.0 - bounciness;
  52295. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52296. var num15 = gradient * num4;
  52297. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52298. var num3 = Math.floor(num65);
  52299. var num13 = num3 + 1.0;
  52300. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52301. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52302. var num7 = (num8 + num12) * 0.5;
  52303. var num6 = gradient - num7;
  52304. var num2 = num7 - num8;
  52305. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52306. };
  52307. return BounceEase;
  52308. }(EasingFunction));
  52309. BABYLON.BounceEase = BounceEase;
  52310. var CubicEase = /** @class */ (function (_super) {
  52311. __extends(CubicEase, _super);
  52312. function CubicEase() {
  52313. return _super !== null && _super.apply(this, arguments) || this;
  52314. }
  52315. CubicEase.prototype.easeInCore = function (gradient) {
  52316. return (gradient * gradient * gradient);
  52317. };
  52318. return CubicEase;
  52319. }(EasingFunction));
  52320. BABYLON.CubicEase = CubicEase;
  52321. var ElasticEase = /** @class */ (function (_super) {
  52322. __extends(ElasticEase, _super);
  52323. function ElasticEase(oscillations, springiness) {
  52324. if (oscillations === void 0) { oscillations = 3; }
  52325. if (springiness === void 0) { springiness = 3; }
  52326. var _this = _super.call(this) || this;
  52327. _this.oscillations = oscillations;
  52328. _this.springiness = springiness;
  52329. return _this;
  52330. }
  52331. ElasticEase.prototype.easeInCore = function (gradient) {
  52332. var num2;
  52333. var num3 = Math.max(0.0, this.oscillations);
  52334. var num = Math.max(0.0, this.springiness);
  52335. if (num == 0) {
  52336. num2 = gradient;
  52337. }
  52338. else {
  52339. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52340. }
  52341. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52342. };
  52343. return ElasticEase;
  52344. }(EasingFunction));
  52345. BABYLON.ElasticEase = ElasticEase;
  52346. var ExponentialEase = /** @class */ (function (_super) {
  52347. __extends(ExponentialEase, _super);
  52348. function ExponentialEase(exponent) {
  52349. if (exponent === void 0) { exponent = 2; }
  52350. var _this = _super.call(this) || this;
  52351. _this.exponent = exponent;
  52352. return _this;
  52353. }
  52354. ExponentialEase.prototype.easeInCore = function (gradient) {
  52355. if (this.exponent <= 0) {
  52356. return gradient;
  52357. }
  52358. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52359. };
  52360. return ExponentialEase;
  52361. }(EasingFunction));
  52362. BABYLON.ExponentialEase = ExponentialEase;
  52363. var PowerEase = /** @class */ (function (_super) {
  52364. __extends(PowerEase, _super);
  52365. function PowerEase(power) {
  52366. if (power === void 0) { power = 2; }
  52367. var _this = _super.call(this) || this;
  52368. _this.power = power;
  52369. return _this;
  52370. }
  52371. PowerEase.prototype.easeInCore = function (gradient) {
  52372. var y = Math.max(0.0, this.power);
  52373. return Math.pow(gradient, y);
  52374. };
  52375. return PowerEase;
  52376. }(EasingFunction));
  52377. BABYLON.PowerEase = PowerEase;
  52378. var QuadraticEase = /** @class */ (function (_super) {
  52379. __extends(QuadraticEase, _super);
  52380. function QuadraticEase() {
  52381. return _super !== null && _super.apply(this, arguments) || this;
  52382. }
  52383. QuadraticEase.prototype.easeInCore = function (gradient) {
  52384. return (gradient * gradient);
  52385. };
  52386. return QuadraticEase;
  52387. }(EasingFunction));
  52388. BABYLON.QuadraticEase = QuadraticEase;
  52389. var QuarticEase = /** @class */ (function (_super) {
  52390. __extends(QuarticEase, _super);
  52391. function QuarticEase() {
  52392. return _super !== null && _super.apply(this, arguments) || this;
  52393. }
  52394. QuarticEase.prototype.easeInCore = function (gradient) {
  52395. return (gradient * gradient * gradient * gradient);
  52396. };
  52397. return QuarticEase;
  52398. }(EasingFunction));
  52399. BABYLON.QuarticEase = QuarticEase;
  52400. var QuinticEase = /** @class */ (function (_super) {
  52401. __extends(QuinticEase, _super);
  52402. function QuinticEase() {
  52403. return _super !== null && _super.apply(this, arguments) || this;
  52404. }
  52405. QuinticEase.prototype.easeInCore = function (gradient) {
  52406. return (gradient * gradient * gradient * gradient * gradient);
  52407. };
  52408. return QuinticEase;
  52409. }(EasingFunction));
  52410. BABYLON.QuinticEase = QuinticEase;
  52411. var SineEase = /** @class */ (function (_super) {
  52412. __extends(SineEase, _super);
  52413. function SineEase() {
  52414. return _super !== null && _super.apply(this, arguments) || this;
  52415. }
  52416. SineEase.prototype.easeInCore = function (gradient) {
  52417. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52418. };
  52419. return SineEase;
  52420. }(EasingFunction));
  52421. BABYLON.SineEase = SineEase;
  52422. var BezierCurveEase = /** @class */ (function (_super) {
  52423. __extends(BezierCurveEase, _super);
  52424. function BezierCurveEase(x1, y1, x2, y2) {
  52425. if (x1 === void 0) { x1 = 0; }
  52426. if (y1 === void 0) { y1 = 0; }
  52427. if (x2 === void 0) { x2 = 1; }
  52428. if (y2 === void 0) { y2 = 1; }
  52429. var _this = _super.call(this) || this;
  52430. _this.x1 = x1;
  52431. _this.y1 = y1;
  52432. _this.x2 = x2;
  52433. _this.y2 = y2;
  52434. return _this;
  52435. }
  52436. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52437. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52438. };
  52439. return BezierCurveEase;
  52440. }(EasingFunction));
  52441. BABYLON.BezierCurveEase = BezierCurveEase;
  52442. })(BABYLON || (BABYLON = {}));
  52443. //# sourceMappingURL=babylon.easing.js.map
  52444. var BABYLON;
  52445. (function (BABYLON) {
  52446. /**
  52447. * A Condition applied to an Action
  52448. */
  52449. var Condition = /** @class */ (function () {
  52450. /**
  52451. * Creates a new Condition
  52452. * @param actionManager the manager of the action the condition is applied to
  52453. */
  52454. function Condition(actionManager) {
  52455. this._actionManager = actionManager;
  52456. }
  52457. /**
  52458. * Check if the current condition is valid
  52459. * @returns a boolean
  52460. */
  52461. Condition.prototype.isValid = function () {
  52462. return true;
  52463. };
  52464. /**
  52465. * Internal only
  52466. * @hidden
  52467. */
  52468. Condition.prototype._getProperty = function (propertyPath) {
  52469. return this._actionManager._getProperty(propertyPath);
  52470. };
  52471. /**
  52472. * Internal only
  52473. * @hidden
  52474. */
  52475. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52476. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52477. };
  52478. /**
  52479. * Serialize placeholder for child classes
  52480. * @returns the serialized object
  52481. */
  52482. Condition.prototype.serialize = function () {
  52483. };
  52484. /**
  52485. * Internal only
  52486. * @hidden
  52487. */
  52488. Condition.prototype._serialize = function (serializedCondition) {
  52489. return {
  52490. type: 2,
  52491. children: [],
  52492. name: serializedCondition.name,
  52493. properties: serializedCondition.properties
  52494. };
  52495. };
  52496. return Condition;
  52497. }());
  52498. BABYLON.Condition = Condition;
  52499. /**
  52500. * Defines specific conditional operators as extensions of Condition
  52501. */
  52502. var ValueCondition = /** @class */ (function (_super) {
  52503. __extends(ValueCondition, _super);
  52504. /**
  52505. * Creates a new ValueCondition
  52506. * @param actionManager manager for the action the condition applies to
  52507. * @param target for the action
  52508. * @param propertyPath path to specify the property of the target the conditional operator uses
  52509. * @param value the value compared by the conditional operator against the current value of the property
  52510. * @param operator the conditional operator, default ValueCondition.IsEqual
  52511. */
  52512. function ValueCondition(actionManager, target,
  52513. /** path to specify the property of the target the conditional operator uses */
  52514. propertyPath,
  52515. /** the value compared by the conditional operator against the current value of the property */
  52516. value,
  52517. /** the conditional operator, default ValueCondition.IsEqual */
  52518. operator) {
  52519. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52520. var _this = _super.call(this, actionManager) || this;
  52521. _this.propertyPath = propertyPath;
  52522. _this.value = value;
  52523. _this.operator = operator;
  52524. _this._target = target;
  52525. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52526. _this._property = _this._getProperty(_this.propertyPath);
  52527. return _this;
  52528. }
  52529. Object.defineProperty(ValueCondition, "IsEqual", {
  52530. /**
  52531. * returns the number for IsEqual
  52532. */
  52533. get: function () {
  52534. return ValueCondition._IsEqual;
  52535. },
  52536. enumerable: true,
  52537. configurable: true
  52538. });
  52539. Object.defineProperty(ValueCondition, "IsDifferent", {
  52540. /**
  52541. * Returns the number for IsDifferent
  52542. */
  52543. get: function () {
  52544. return ValueCondition._IsDifferent;
  52545. },
  52546. enumerable: true,
  52547. configurable: true
  52548. });
  52549. Object.defineProperty(ValueCondition, "IsGreater", {
  52550. /**
  52551. * Returns the number for IsGreater
  52552. */
  52553. get: function () {
  52554. return ValueCondition._IsGreater;
  52555. },
  52556. enumerable: true,
  52557. configurable: true
  52558. });
  52559. Object.defineProperty(ValueCondition, "IsLesser", {
  52560. /**
  52561. * Returns the number for IsLesser
  52562. */
  52563. get: function () {
  52564. return ValueCondition._IsLesser;
  52565. },
  52566. enumerable: true,
  52567. configurable: true
  52568. });
  52569. /**
  52570. * Compares the given value with the property value for the specified conditional operator
  52571. * @returns the result of the comparison
  52572. */
  52573. ValueCondition.prototype.isValid = function () {
  52574. switch (this.operator) {
  52575. case ValueCondition.IsGreater:
  52576. return this._effectiveTarget[this._property] > this.value;
  52577. case ValueCondition.IsLesser:
  52578. return this._effectiveTarget[this._property] < this.value;
  52579. case ValueCondition.IsEqual:
  52580. case ValueCondition.IsDifferent:
  52581. var check;
  52582. if (this.value.equals) {
  52583. check = this.value.equals(this._effectiveTarget[this._property]);
  52584. }
  52585. else {
  52586. check = this.value === this._effectiveTarget[this._property];
  52587. }
  52588. return this.operator === ValueCondition.IsEqual ? check : !check;
  52589. }
  52590. return false;
  52591. };
  52592. /**
  52593. * Serialize the ValueCondition into a JSON compatible object
  52594. * @returns serialization object
  52595. */
  52596. ValueCondition.prototype.serialize = function () {
  52597. return this._serialize({
  52598. name: "ValueCondition",
  52599. properties: [
  52600. BABYLON.Action._GetTargetProperty(this._target),
  52601. { name: "propertyPath", value: this.propertyPath },
  52602. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52603. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52604. ]
  52605. });
  52606. };
  52607. /**
  52608. * Gets the name of the conditional operator for the ValueCondition
  52609. * @param operator the conditional operator
  52610. * @returns the name
  52611. */
  52612. ValueCondition.GetOperatorName = function (operator) {
  52613. switch (operator) {
  52614. case ValueCondition._IsEqual: return "IsEqual";
  52615. case ValueCondition._IsDifferent: return "IsDifferent";
  52616. case ValueCondition._IsGreater: return "IsGreater";
  52617. case ValueCondition._IsLesser: return "IsLesser";
  52618. default: return "";
  52619. }
  52620. };
  52621. /**
  52622. * Internal only
  52623. * @hidden
  52624. */
  52625. ValueCondition._IsEqual = 0;
  52626. /**
  52627. * Internal only
  52628. * @hidden
  52629. */
  52630. ValueCondition._IsDifferent = 1;
  52631. /**
  52632. * Internal only
  52633. * @hidden
  52634. */
  52635. ValueCondition._IsGreater = 2;
  52636. /**
  52637. * Internal only
  52638. * @hidden
  52639. */
  52640. ValueCondition._IsLesser = 3;
  52641. return ValueCondition;
  52642. }(Condition));
  52643. BABYLON.ValueCondition = ValueCondition;
  52644. /**
  52645. * Defines a predicate condition as an extension of Condition
  52646. */
  52647. var PredicateCondition = /** @class */ (function (_super) {
  52648. __extends(PredicateCondition, _super);
  52649. /**
  52650. * Creates a new PredicateCondition
  52651. * @param actionManager manager for the action the condition applies to
  52652. * @param predicate defines the predicate function used to validate the condition
  52653. */
  52654. function PredicateCondition(actionManager,
  52655. /** defines the predicate function used to validate the condition */
  52656. predicate) {
  52657. var _this = _super.call(this, actionManager) || this;
  52658. _this.predicate = predicate;
  52659. return _this;
  52660. }
  52661. /**
  52662. * @returns the validity of the predicate condition
  52663. */
  52664. PredicateCondition.prototype.isValid = function () {
  52665. return this.predicate();
  52666. };
  52667. return PredicateCondition;
  52668. }(Condition));
  52669. BABYLON.PredicateCondition = PredicateCondition;
  52670. /**
  52671. * Defines a state condition as an extension of Condition
  52672. */
  52673. var StateCondition = /** @class */ (function (_super) {
  52674. __extends(StateCondition, _super);
  52675. /**
  52676. * Creates a new StateCondition
  52677. * @param actionManager manager for the action the condition applies to
  52678. * @param target of the condition
  52679. * @param value to compare with target state
  52680. */
  52681. function StateCondition(actionManager, target, value) {
  52682. var _this = _super.call(this, actionManager) || this;
  52683. _this.value = value;
  52684. _this._target = target;
  52685. return _this;
  52686. }
  52687. /**
  52688. * @returns the validity of the state
  52689. */
  52690. StateCondition.prototype.isValid = function () {
  52691. return this._target.state === this.value;
  52692. };
  52693. /**
  52694. * Serialize the StateCondition into a JSON compatible object
  52695. * @returns serialization object
  52696. */
  52697. StateCondition.prototype.serialize = function () {
  52698. return this._serialize({
  52699. name: "StateCondition",
  52700. properties: [
  52701. BABYLON.Action._GetTargetProperty(this._target),
  52702. { name: "value", value: this.value }
  52703. ]
  52704. });
  52705. };
  52706. return StateCondition;
  52707. }(Condition));
  52708. BABYLON.StateCondition = StateCondition;
  52709. })(BABYLON || (BABYLON = {}));
  52710. //# sourceMappingURL=babylon.condition.js.map
  52711. var BABYLON;
  52712. (function (BABYLON) {
  52713. /**
  52714. * The action to be carried out following a trigger
  52715. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52716. */
  52717. var Action = /** @class */ (function () {
  52718. /**
  52719. * Creates a new Action
  52720. * @param triggerOptions the trigger, with or without parameters, for the action
  52721. * @param condition an optional determinant of action
  52722. */
  52723. function Action(
  52724. /** the trigger, with or without parameters, for the action */
  52725. triggerOptions, condition) {
  52726. this.triggerOptions = triggerOptions;
  52727. /**
  52728. * An event triggered prior to action being executed.
  52729. */
  52730. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52731. if (triggerOptions.parameter) {
  52732. this.trigger = triggerOptions.trigger;
  52733. this._triggerParameter = triggerOptions.parameter;
  52734. }
  52735. else {
  52736. this.trigger = triggerOptions;
  52737. }
  52738. this._nextActiveAction = this;
  52739. this._condition = condition;
  52740. }
  52741. /**
  52742. * Internal only
  52743. * @hidden
  52744. */
  52745. Action.prototype._prepare = function () {
  52746. };
  52747. /**
  52748. * Gets the trigger parameters
  52749. * @returns the trigger parameters
  52750. */
  52751. Action.prototype.getTriggerParameter = function () {
  52752. return this._triggerParameter;
  52753. };
  52754. /**
  52755. * Internal only - executes current action event
  52756. * @hidden
  52757. */
  52758. Action.prototype._executeCurrent = function (evt) {
  52759. if (this._nextActiveAction._condition) {
  52760. var condition = this._nextActiveAction._condition;
  52761. var currentRenderId = this._actionManager.getScene().getRenderId();
  52762. // We cache the current evaluation for the current frame
  52763. if (condition._evaluationId === currentRenderId) {
  52764. if (!condition._currentResult) {
  52765. return;
  52766. }
  52767. }
  52768. else {
  52769. condition._evaluationId = currentRenderId;
  52770. if (!condition.isValid()) {
  52771. condition._currentResult = false;
  52772. return;
  52773. }
  52774. condition._currentResult = true;
  52775. }
  52776. }
  52777. this.onBeforeExecuteObservable.notifyObservers(this);
  52778. this._nextActiveAction.execute(evt);
  52779. this.skipToNextActiveAction();
  52780. };
  52781. /**
  52782. * Execute placeholder for child classes
  52783. * @param evt optional action event
  52784. */
  52785. Action.prototype.execute = function (evt) {
  52786. };
  52787. /**
  52788. * Skips to next active action
  52789. */
  52790. Action.prototype.skipToNextActiveAction = function () {
  52791. if (this._nextActiveAction._child) {
  52792. if (!this._nextActiveAction._child._actionManager) {
  52793. this._nextActiveAction._child._actionManager = this._actionManager;
  52794. }
  52795. this._nextActiveAction = this._nextActiveAction._child;
  52796. }
  52797. else {
  52798. this._nextActiveAction = this;
  52799. }
  52800. };
  52801. /**
  52802. * Adds action to chain of actions, may be a DoNothingAction
  52803. * @param action defines the next action to execute
  52804. * @returns The action passed in
  52805. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52806. */
  52807. Action.prototype.then = function (action) {
  52808. this._child = action;
  52809. action._actionManager = this._actionManager;
  52810. action._prepare();
  52811. return action;
  52812. };
  52813. /**
  52814. * Internal only
  52815. * @hidden
  52816. */
  52817. Action.prototype._getProperty = function (propertyPath) {
  52818. return this._actionManager._getProperty(propertyPath);
  52819. };
  52820. /**
  52821. * Internal only
  52822. * @hidden
  52823. */
  52824. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52825. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52826. };
  52827. /**
  52828. * Serialize placeholder for child classes
  52829. * @param parent of child
  52830. * @returns the serialized object
  52831. */
  52832. Action.prototype.serialize = function (parent) {
  52833. };
  52834. /**
  52835. * Internal only called by serialize
  52836. * @hidden
  52837. */
  52838. Action.prototype._serialize = function (serializedAction, parent) {
  52839. var serializationObject = {
  52840. type: 1,
  52841. children: [],
  52842. name: serializedAction.name,
  52843. properties: serializedAction.properties || []
  52844. };
  52845. // Serialize child
  52846. if (this._child) {
  52847. this._child.serialize(serializationObject);
  52848. }
  52849. // Check if "this" has a condition
  52850. if (this._condition) {
  52851. var serializedCondition = this._condition.serialize();
  52852. serializedCondition.children.push(serializationObject);
  52853. if (parent) {
  52854. parent.children.push(serializedCondition);
  52855. }
  52856. return serializedCondition;
  52857. }
  52858. if (parent) {
  52859. parent.children.push(serializationObject);
  52860. }
  52861. return serializationObject;
  52862. };
  52863. /**
  52864. * Internal only
  52865. * @hidden
  52866. */
  52867. Action._SerializeValueAsString = function (value) {
  52868. if (typeof value === "number") {
  52869. return value.toString();
  52870. }
  52871. if (typeof value === "boolean") {
  52872. return value ? "true" : "false";
  52873. }
  52874. if (value instanceof BABYLON.Vector2) {
  52875. return value.x + ", " + value.y;
  52876. }
  52877. if (value instanceof BABYLON.Vector3) {
  52878. return value.x + ", " + value.y + ", " + value.z;
  52879. }
  52880. if (value instanceof BABYLON.Color3) {
  52881. return value.r + ", " + value.g + ", " + value.b;
  52882. }
  52883. if (value instanceof BABYLON.Color4) {
  52884. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52885. }
  52886. return value; // string
  52887. };
  52888. /**
  52889. * Internal only
  52890. * @hidden
  52891. */
  52892. Action._GetTargetProperty = function (target) {
  52893. return {
  52894. name: "target",
  52895. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52896. : target instanceof BABYLON.Light ? "LightProperties"
  52897. : target instanceof BABYLON.Camera ? "CameraProperties"
  52898. : "SceneProperties",
  52899. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52900. };
  52901. };
  52902. return Action;
  52903. }());
  52904. BABYLON.Action = Action;
  52905. })(BABYLON || (BABYLON = {}));
  52906. //# sourceMappingURL=babylon.action.js.map
  52907. var BABYLON;
  52908. (function (BABYLON) {
  52909. /**
  52910. * ActionEvent is the event being sent when an action is triggered.
  52911. */
  52912. var ActionEvent = /** @class */ (function () {
  52913. /**
  52914. * Creates a new ActionEvent
  52915. * @param source The mesh or sprite that triggered the action
  52916. * @param pointerX The X mouse cursor position at the time of the event
  52917. * @param pointerY The Y mouse cursor position at the time of the event
  52918. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52919. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52920. * @param additionalData additional data for the event
  52921. */
  52922. function ActionEvent(
  52923. /** The mesh or sprite that triggered the action */
  52924. source,
  52925. /** The X mouse cursor position at the time of the event */
  52926. pointerX,
  52927. /** The Y mouse cursor position at the time of the event */
  52928. pointerY,
  52929. /** The mesh that is currently pointed at (can be null) */
  52930. meshUnderPointer,
  52931. /** the original (browser) event that triggered the ActionEvent */
  52932. sourceEvent,
  52933. /** additional data for the event */
  52934. additionalData) {
  52935. this.source = source;
  52936. this.pointerX = pointerX;
  52937. this.pointerY = pointerY;
  52938. this.meshUnderPointer = meshUnderPointer;
  52939. this.sourceEvent = sourceEvent;
  52940. this.additionalData = additionalData;
  52941. }
  52942. /**
  52943. * Helper function to auto-create an ActionEvent from a source mesh.
  52944. * @param source The source mesh that triggered the event
  52945. * @param evt The original (browser) event
  52946. * @param additionalData additional data for the event
  52947. * @returns the new ActionEvent
  52948. */
  52949. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52950. var scene = source.getScene();
  52951. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52952. };
  52953. /**
  52954. * Helper function to auto-create an ActionEvent from a source sprite
  52955. * @param source The source sprite that triggered the event
  52956. * @param scene Scene associated with the sprite
  52957. * @param evt The original (browser) event
  52958. * @param additionalData additional data for the event
  52959. * @returns the new ActionEvent
  52960. */
  52961. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52962. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52963. };
  52964. /**
  52965. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52966. * @param scene the scene where the event occurred
  52967. * @param evt The original (browser) event
  52968. * @returns the new ActionEvent
  52969. */
  52970. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52971. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52972. };
  52973. /**
  52974. * Helper function to auto-create an ActionEvent from a primitive
  52975. * @param prim defines the target primitive
  52976. * @param pointerPos defines the pointer position
  52977. * @param evt The original (browser) event
  52978. * @param additionalData additional data for the event
  52979. * @returns the new ActionEvent
  52980. */
  52981. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52982. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52983. };
  52984. return ActionEvent;
  52985. }());
  52986. BABYLON.ActionEvent = ActionEvent;
  52987. /**
  52988. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52989. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52990. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52991. */
  52992. var ActionManager = /** @class */ (function () {
  52993. /**
  52994. * Creates a new action manager
  52995. * @param scene defines the hosting scene
  52996. */
  52997. function ActionManager(scene) {
  52998. // Members
  52999. /** Gets the list of actions */
  53000. this.actions = new Array();
  53001. /** Gets the cursor to use when hovering items */
  53002. this.hoverCursor = '';
  53003. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53004. scene._actionManagers.push(this);
  53005. }
  53006. Object.defineProperty(ActionManager, "NothingTrigger", {
  53007. /**
  53008. * Nothing
  53009. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53010. */
  53011. get: function () {
  53012. return ActionManager._NothingTrigger;
  53013. },
  53014. enumerable: true,
  53015. configurable: true
  53016. });
  53017. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53018. /**
  53019. * On pick
  53020. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53021. */
  53022. get: function () {
  53023. return ActionManager._OnPickTrigger;
  53024. },
  53025. enumerable: true,
  53026. configurable: true
  53027. });
  53028. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53029. /**
  53030. * On left pick
  53031. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53032. */
  53033. get: function () {
  53034. return ActionManager._OnLeftPickTrigger;
  53035. },
  53036. enumerable: true,
  53037. configurable: true
  53038. });
  53039. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53040. /**
  53041. * On right pick
  53042. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53043. */
  53044. get: function () {
  53045. return ActionManager._OnRightPickTrigger;
  53046. },
  53047. enumerable: true,
  53048. configurable: true
  53049. });
  53050. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53051. /**
  53052. * On center pick
  53053. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53054. */
  53055. get: function () {
  53056. return ActionManager._OnCenterPickTrigger;
  53057. },
  53058. enumerable: true,
  53059. configurable: true
  53060. });
  53061. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53062. /**
  53063. * On pick down
  53064. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53065. */
  53066. get: function () {
  53067. return ActionManager._OnPickDownTrigger;
  53068. },
  53069. enumerable: true,
  53070. configurable: true
  53071. });
  53072. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53073. /**
  53074. * On double pick
  53075. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53076. */
  53077. get: function () {
  53078. return ActionManager._OnDoublePickTrigger;
  53079. },
  53080. enumerable: true,
  53081. configurable: true
  53082. });
  53083. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53084. /**
  53085. * On pick up
  53086. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53087. */
  53088. get: function () {
  53089. return ActionManager._OnPickUpTrigger;
  53090. },
  53091. enumerable: true,
  53092. configurable: true
  53093. });
  53094. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53095. /**
  53096. * On pick out.
  53097. * This trigger will only be raised if you also declared a OnPickDown
  53098. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53099. */
  53100. get: function () {
  53101. return ActionManager._OnPickOutTrigger;
  53102. },
  53103. enumerable: true,
  53104. configurable: true
  53105. });
  53106. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53107. /**
  53108. * On long press
  53109. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53110. */
  53111. get: function () {
  53112. return ActionManager._OnLongPressTrigger;
  53113. },
  53114. enumerable: true,
  53115. configurable: true
  53116. });
  53117. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53118. /**
  53119. * On pointer over
  53120. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53121. */
  53122. get: function () {
  53123. return ActionManager._OnPointerOverTrigger;
  53124. },
  53125. enumerable: true,
  53126. configurable: true
  53127. });
  53128. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53129. /**
  53130. * On pointer out
  53131. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53132. */
  53133. get: function () {
  53134. return ActionManager._OnPointerOutTrigger;
  53135. },
  53136. enumerable: true,
  53137. configurable: true
  53138. });
  53139. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53140. /**
  53141. * On every frame
  53142. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53143. */
  53144. get: function () {
  53145. return ActionManager._OnEveryFrameTrigger;
  53146. },
  53147. enumerable: true,
  53148. configurable: true
  53149. });
  53150. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53151. /**
  53152. * On intersection enter
  53153. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53154. */
  53155. get: function () {
  53156. return ActionManager._OnIntersectionEnterTrigger;
  53157. },
  53158. enumerable: true,
  53159. configurable: true
  53160. });
  53161. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53162. /**
  53163. * On intersection exit
  53164. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53165. */
  53166. get: function () {
  53167. return ActionManager._OnIntersectionExitTrigger;
  53168. },
  53169. enumerable: true,
  53170. configurable: true
  53171. });
  53172. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53173. /**
  53174. * On key down
  53175. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53176. */
  53177. get: function () {
  53178. return ActionManager._OnKeyDownTrigger;
  53179. },
  53180. enumerable: true,
  53181. configurable: true
  53182. });
  53183. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53184. /**
  53185. * On key up
  53186. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53187. */
  53188. get: function () {
  53189. return ActionManager._OnKeyUpTrigger;
  53190. },
  53191. enumerable: true,
  53192. configurable: true
  53193. });
  53194. // Methods
  53195. /**
  53196. * Releases all associated resources
  53197. */
  53198. ActionManager.prototype.dispose = function () {
  53199. var index = this._scene._actionManagers.indexOf(this);
  53200. for (var i = 0; i < this.actions.length; i++) {
  53201. var action = this.actions[i];
  53202. ActionManager.Triggers[action.trigger]--;
  53203. if (ActionManager.Triggers[action.trigger] === 0) {
  53204. delete ActionManager.Triggers[action.trigger];
  53205. }
  53206. }
  53207. if (index > -1) {
  53208. this._scene._actionManagers.splice(index, 1);
  53209. }
  53210. };
  53211. /**
  53212. * Gets hosting scene
  53213. * @returns the hosting scene
  53214. */
  53215. ActionManager.prototype.getScene = function () {
  53216. return this._scene;
  53217. };
  53218. /**
  53219. * Does this action manager handles actions of any of the given triggers
  53220. * @param triggers defines the triggers to be tested
  53221. * @return a boolean indicating whether one (or more) of the triggers is handled
  53222. */
  53223. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53224. for (var index = 0; index < this.actions.length; index++) {
  53225. var action = this.actions[index];
  53226. if (triggers.indexOf(action.trigger) > -1) {
  53227. return true;
  53228. }
  53229. }
  53230. return false;
  53231. };
  53232. /**
  53233. * Does this action manager handles actions of a given trigger
  53234. * @param trigger defines the trigger to be tested
  53235. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53236. * @return whether the trigger is handled
  53237. */
  53238. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53239. for (var index = 0; index < this.actions.length; index++) {
  53240. var action = this.actions[index];
  53241. if (action.trigger === trigger) {
  53242. if (parameterPredicate) {
  53243. if (parameterPredicate(action.getTriggerParameter())) {
  53244. return true;
  53245. }
  53246. }
  53247. else {
  53248. return true;
  53249. }
  53250. }
  53251. }
  53252. return false;
  53253. };
  53254. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53255. /**
  53256. * Does this action manager has pointer triggers
  53257. */
  53258. get: function () {
  53259. for (var index = 0; index < this.actions.length; index++) {
  53260. var action = this.actions[index];
  53261. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53262. return true;
  53263. }
  53264. }
  53265. return false;
  53266. },
  53267. enumerable: true,
  53268. configurable: true
  53269. });
  53270. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53271. /**
  53272. * Does this action manager has pick triggers
  53273. */
  53274. get: function () {
  53275. for (var index = 0; index < this.actions.length; index++) {
  53276. var action = this.actions[index];
  53277. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53278. return true;
  53279. }
  53280. }
  53281. return false;
  53282. },
  53283. enumerable: true,
  53284. configurable: true
  53285. });
  53286. Object.defineProperty(ActionManager, "HasTriggers", {
  53287. /**
  53288. * Does exist one action manager with at least one trigger
  53289. **/
  53290. get: function () {
  53291. for (var t in ActionManager.Triggers) {
  53292. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53293. return true;
  53294. }
  53295. }
  53296. return false;
  53297. },
  53298. enumerable: true,
  53299. configurable: true
  53300. });
  53301. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53302. /**
  53303. * Does exist one action manager with at least one pick trigger
  53304. **/
  53305. get: function () {
  53306. for (var t in ActionManager.Triggers) {
  53307. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53308. var t_int = parseInt(t);
  53309. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53310. return true;
  53311. }
  53312. }
  53313. }
  53314. return false;
  53315. },
  53316. enumerable: true,
  53317. configurable: true
  53318. });
  53319. /**
  53320. * Does exist one action manager that handles actions of a given trigger
  53321. * @param trigger defines the trigger to be tested
  53322. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53323. **/
  53324. ActionManager.HasSpecificTrigger = function (trigger) {
  53325. for (var t in ActionManager.Triggers) {
  53326. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53327. var t_int = parseInt(t);
  53328. if (t_int === trigger) {
  53329. return true;
  53330. }
  53331. }
  53332. }
  53333. return false;
  53334. };
  53335. /**
  53336. * Registers an action to this action manager
  53337. * @param action defines the action to be registered
  53338. * @return the action amended (prepared) after registration
  53339. */
  53340. ActionManager.prototype.registerAction = function (action) {
  53341. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53342. if (this.getScene().actionManager !== this) {
  53343. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53344. return null;
  53345. }
  53346. }
  53347. this.actions.push(action);
  53348. if (ActionManager.Triggers[action.trigger]) {
  53349. ActionManager.Triggers[action.trigger]++;
  53350. }
  53351. else {
  53352. ActionManager.Triggers[action.trigger] = 1;
  53353. }
  53354. action._actionManager = this;
  53355. action._prepare();
  53356. return action;
  53357. };
  53358. /**
  53359. * Unregisters an action to this action manager
  53360. * @param action defines the action to be unregistered
  53361. * @return a boolean indicating whether the action has been unregistered
  53362. */
  53363. ActionManager.prototype.unregisterAction = function (action) {
  53364. var index = this.actions.indexOf(action);
  53365. if (index !== -1) {
  53366. this.actions.splice(index, 1);
  53367. ActionManager.Triggers[action.trigger] -= 1;
  53368. if (ActionManager.Triggers[action.trigger] === 0) {
  53369. delete ActionManager.Triggers[action.trigger];
  53370. }
  53371. delete action._actionManager;
  53372. return true;
  53373. }
  53374. return false;
  53375. };
  53376. /**
  53377. * Process a specific trigger
  53378. * @param trigger defines the trigger to process
  53379. * @param evt defines the event details to be processed
  53380. */
  53381. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53382. for (var index = 0; index < this.actions.length; index++) {
  53383. var action = this.actions[index];
  53384. if (action.trigger === trigger) {
  53385. if (evt) {
  53386. if (trigger === ActionManager.OnKeyUpTrigger
  53387. || trigger === ActionManager.OnKeyDownTrigger) {
  53388. var parameter = action.getTriggerParameter();
  53389. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53390. if (!parameter.toLowerCase) {
  53391. continue;
  53392. }
  53393. var lowerCase = parameter.toLowerCase();
  53394. if (lowerCase !== evt.sourceEvent.key) {
  53395. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53396. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53397. if (actualkey !== lowerCase) {
  53398. continue;
  53399. }
  53400. }
  53401. }
  53402. }
  53403. }
  53404. action._executeCurrent(evt);
  53405. }
  53406. }
  53407. };
  53408. /** @hidden */
  53409. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53410. var properties = propertyPath.split(".");
  53411. for (var index = 0; index < properties.length - 1; index++) {
  53412. target = target[properties[index]];
  53413. }
  53414. return target;
  53415. };
  53416. /** @hidden */
  53417. ActionManager.prototype._getProperty = function (propertyPath) {
  53418. var properties = propertyPath.split(".");
  53419. return properties[properties.length - 1];
  53420. };
  53421. /**
  53422. * Serialize this manager to a JSON object
  53423. * @param name defines the property name to store this manager
  53424. * @returns a JSON representation of this manager
  53425. */
  53426. ActionManager.prototype.serialize = function (name) {
  53427. var root = {
  53428. children: new Array(),
  53429. name: name,
  53430. type: 3,
  53431. properties: new Array() // Empty for root but required
  53432. };
  53433. for (var i = 0; i < this.actions.length; i++) {
  53434. var triggerObject = {
  53435. type: 0,
  53436. children: new Array(),
  53437. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53438. properties: new Array()
  53439. };
  53440. var triggerOptions = this.actions[i].triggerOptions;
  53441. if (triggerOptions && typeof triggerOptions !== "number") {
  53442. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53443. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53444. }
  53445. else {
  53446. var parameter = {};
  53447. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53448. if (triggerOptions.parameter.mesh) {
  53449. parameter._meshId = triggerOptions.parameter.mesh.id;
  53450. }
  53451. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53452. }
  53453. }
  53454. // Serialize child action, recursively
  53455. this.actions[i].serialize(triggerObject);
  53456. // Add serialized trigger
  53457. root.children.push(triggerObject);
  53458. }
  53459. return root;
  53460. };
  53461. /**
  53462. * Creates a new ActionManager from a JSON data
  53463. * @param parsedActions defines the JSON data to read from
  53464. * @param object defines the hosting mesh
  53465. * @param scene defines the hosting scene
  53466. */
  53467. ActionManager.Parse = function (parsedActions, object, scene) {
  53468. var actionManager = new ActionManager(scene);
  53469. if (object === null)
  53470. scene.actionManager = actionManager;
  53471. else
  53472. object.actionManager = actionManager;
  53473. // instanciate a new object
  53474. var instanciate = function (name, params) {
  53475. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53476. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53477. newInstance.constructor.apply(newInstance, params);
  53478. return newInstance;
  53479. };
  53480. var parseParameter = function (name, value, target, propertyPath) {
  53481. if (propertyPath === null) {
  53482. // String, boolean or float
  53483. var floatValue = parseFloat(value);
  53484. if (value === "true" || value === "false")
  53485. return value === "true";
  53486. else
  53487. return isNaN(floatValue) ? value : floatValue;
  53488. }
  53489. var effectiveTarget = propertyPath.split(".");
  53490. var values = value.split(",");
  53491. // Get effective Target
  53492. for (var i = 0; i < effectiveTarget.length; i++) {
  53493. target = target[effectiveTarget[i]];
  53494. }
  53495. // Return appropriate value with its type
  53496. if (typeof (target) === "boolean")
  53497. return values[0] === "true";
  53498. if (typeof (target) === "string")
  53499. return values[0];
  53500. // Parameters with multiple values such as Vector3 etc.
  53501. var split = new Array();
  53502. for (var i = 0; i < values.length; i++)
  53503. split.push(parseFloat(values[i]));
  53504. if (target instanceof BABYLON.Vector3)
  53505. return BABYLON.Vector3.FromArray(split);
  53506. if (target instanceof BABYLON.Vector4)
  53507. return BABYLON.Vector4.FromArray(split);
  53508. if (target instanceof BABYLON.Color3)
  53509. return BABYLON.Color3.FromArray(split);
  53510. if (target instanceof BABYLON.Color4)
  53511. return BABYLON.Color4.FromArray(split);
  53512. return parseFloat(values[0]);
  53513. };
  53514. // traverse graph per trigger
  53515. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53516. if (combineArray === void 0) { combineArray = null; }
  53517. if (parsedAction.detached)
  53518. return;
  53519. var parameters = new Array();
  53520. var target = null;
  53521. var propertyPath = null;
  53522. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53523. // Parameters
  53524. if (parsedAction.type === 2)
  53525. parameters.push(actionManager);
  53526. else
  53527. parameters.push(trigger);
  53528. if (combine) {
  53529. var actions = new Array();
  53530. for (var j = 0; j < parsedAction.combine.length; j++) {
  53531. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53532. }
  53533. parameters.push(actions);
  53534. }
  53535. else {
  53536. for (var i = 0; i < parsedAction.properties.length; i++) {
  53537. var value = parsedAction.properties[i].value;
  53538. var name = parsedAction.properties[i].name;
  53539. var targetType = parsedAction.properties[i].targetType;
  53540. if (name === "target")
  53541. if (targetType !== null && targetType === "SceneProperties")
  53542. value = target = scene;
  53543. else
  53544. value = target = scene.getNodeByName(value);
  53545. else if (name === "parent")
  53546. value = scene.getNodeByName(value);
  53547. else if (name === "sound")
  53548. value = scene.getSoundByName(value);
  53549. else if (name !== "propertyPath") {
  53550. if (parsedAction.type === 2 && name === "operator")
  53551. value = BABYLON.ValueCondition[value];
  53552. else
  53553. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53554. }
  53555. else {
  53556. propertyPath = value;
  53557. }
  53558. parameters.push(value);
  53559. }
  53560. }
  53561. if (combineArray === null) {
  53562. parameters.push(condition);
  53563. }
  53564. else {
  53565. parameters.push(null);
  53566. }
  53567. // If interpolate value action
  53568. if (parsedAction.name === "InterpolateValueAction") {
  53569. var param = parameters[parameters.length - 2];
  53570. parameters[parameters.length - 1] = param;
  53571. parameters[parameters.length - 2] = condition;
  53572. }
  53573. // Action or condition(s) and not CombineAction
  53574. var newAction = instanciate(parsedAction.name, parameters);
  53575. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53576. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53577. if (action)
  53578. action.then(nothing);
  53579. else
  53580. actionManager.registerAction(nothing);
  53581. action = nothing;
  53582. }
  53583. if (combineArray === null) {
  53584. if (newAction instanceof BABYLON.Condition) {
  53585. condition = newAction;
  53586. newAction = action;
  53587. }
  53588. else {
  53589. condition = null;
  53590. if (action)
  53591. action.then(newAction);
  53592. else
  53593. actionManager.registerAction(newAction);
  53594. }
  53595. }
  53596. else {
  53597. combineArray.push(newAction);
  53598. }
  53599. for (var i = 0; i < parsedAction.children.length; i++)
  53600. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53601. };
  53602. // triggers
  53603. for (var i = 0; i < parsedActions.children.length; i++) {
  53604. var triggerParams;
  53605. var trigger = parsedActions.children[i];
  53606. if (trigger.properties.length > 0) {
  53607. var param = trigger.properties[0].value;
  53608. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53609. if (value._meshId) {
  53610. value.mesh = scene.getMeshByID(value._meshId);
  53611. }
  53612. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53613. }
  53614. else
  53615. triggerParams = ActionManager[trigger.name];
  53616. for (var j = 0; j < trigger.children.length; j++) {
  53617. if (!trigger.detached)
  53618. traverse(trigger.children[j], triggerParams, null, null);
  53619. }
  53620. }
  53621. };
  53622. /**
  53623. * Get a trigger name by index
  53624. * @param trigger defines the trigger index
  53625. * @returns a trigger name
  53626. */
  53627. ActionManager.GetTriggerName = function (trigger) {
  53628. switch (trigger) {
  53629. case 0: return "NothingTrigger";
  53630. case 1: return "OnPickTrigger";
  53631. case 2: return "OnLeftPickTrigger";
  53632. case 3: return "OnRightPickTrigger";
  53633. case 4: return "OnCenterPickTrigger";
  53634. case 5: return "OnPickDownTrigger";
  53635. case 6: return "OnPickUpTrigger";
  53636. case 7: return "OnLongPressTrigger";
  53637. case 8: return "OnPointerOverTrigger";
  53638. case 9: return "OnPointerOutTrigger";
  53639. case 10: return "OnEveryFrameTrigger";
  53640. case 11: return "OnIntersectionEnterTrigger";
  53641. case 12: return "OnIntersectionExitTrigger";
  53642. case 13: return "OnKeyDownTrigger";
  53643. case 14: return "OnKeyUpTrigger";
  53644. case 15: return "OnPickOutTrigger";
  53645. default: return "";
  53646. }
  53647. };
  53648. // Statics
  53649. ActionManager._NothingTrigger = 0;
  53650. ActionManager._OnPickTrigger = 1;
  53651. ActionManager._OnLeftPickTrigger = 2;
  53652. ActionManager._OnRightPickTrigger = 3;
  53653. ActionManager._OnCenterPickTrigger = 4;
  53654. ActionManager._OnPickDownTrigger = 5;
  53655. ActionManager._OnDoublePickTrigger = 6;
  53656. ActionManager._OnPickUpTrigger = 7;
  53657. ActionManager._OnLongPressTrigger = 8;
  53658. ActionManager._OnPointerOverTrigger = 9;
  53659. ActionManager._OnPointerOutTrigger = 10;
  53660. ActionManager._OnEveryFrameTrigger = 11;
  53661. ActionManager._OnIntersectionEnterTrigger = 12;
  53662. ActionManager._OnIntersectionExitTrigger = 13;
  53663. ActionManager._OnKeyDownTrigger = 14;
  53664. ActionManager._OnKeyUpTrigger = 15;
  53665. ActionManager._OnPickOutTrigger = 16;
  53666. /** Gets the list of active triggers */
  53667. ActionManager.Triggers = {};
  53668. return ActionManager;
  53669. }());
  53670. BABYLON.ActionManager = ActionManager;
  53671. })(BABYLON || (BABYLON = {}));
  53672. //# sourceMappingURL=babylon.actionManager.js.map
  53673. var BABYLON;
  53674. (function (BABYLON) {
  53675. var InterpolateValueAction = /** @class */ (function (_super) {
  53676. __extends(InterpolateValueAction, _super);
  53677. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53678. if (duration === void 0) { duration = 1000; }
  53679. var _this = _super.call(this, triggerOptions, condition) || this;
  53680. _this.propertyPath = propertyPath;
  53681. _this.value = value;
  53682. _this.duration = duration;
  53683. _this.stopOtherAnimations = stopOtherAnimations;
  53684. _this.onInterpolationDone = onInterpolationDone;
  53685. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53686. _this._target = _this._effectiveTarget = target;
  53687. return _this;
  53688. }
  53689. InterpolateValueAction.prototype._prepare = function () {
  53690. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53691. this._property = this._getProperty(this.propertyPath);
  53692. };
  53693. InterpolateValueAction.prototype.execute = function () {
  53694. var _this = this;
  53695. var scene = this._actionManager.getScene();
  53696. var keys = [
  53697. {
  53698. frame: 0,
  53699. value: this._effectiveTarget[this._property]
  53700. }, {
  53701. frame: 100,
  53702. value: this.value
  53703. }
  53704. ];
  53705. var dataType;
  53706. if (typeof this.value === "number") {
  53707. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53708. }
  53709. else if (this.value instanceof BABYLON.Color3) {
  53710. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53711. }
  53712. else if (this.value instanceof BABYLON.Vector3) {
  53713. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53714. }
  53715. else if (this.value instanceof BABYLON.Matrix) {
  53716. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53717. }
  53718. else if (this.value instanceof BABYLON.Quaternion) {
  53719. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53720. }
  53721. else {
  53722. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53723. return;
  53724. }
  53725. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53726. animation.setKeys(keys);
  53727. if (this.stopOtherAnimations) {
  53728. scene.stopAnimation(this._effectiveTarget);
  53729. }
  53730. var wrapper = function () {
  53731. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53732. if (_this.onInterpolationDone) {
  53733. _this.onInterpolationDone();
  53734. }
  53735. };
  53736. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53737. };
  53738. InterpolateValueAction.prototype.serialize = function (parent) {
  53739. return _super.prototype._serialize.call(this, {
  53740. name: "InterpolateValueAction",
  53741. properties: [
  53742. BABYLON.Action._GetTargetProperty(this._target),
  53743. { name: "propertyPath", value: this.propertyPath },
  53744. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53745. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53746. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53747. ]
  53748. }, parent);
  53749. };
  53750. return InterpolateValueAction;
  53751. }(BABYLON.Action));
  53752. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53753. })(BABYLON || (BABYLON = {}));
  53754. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53755. var BABYLON;
  53756. (function (BABYLON) {
  53757. var SwitchBooleanAction = /** @class */ (function (_super) {
  53758. __extends(SwitchBooleanAction, _super);
  53759. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53760. var _this = _super.call(this, triggerOptions, condition) || this;
  53761. _this.propertyPath = propertyPath;
  53762. _this._target = _this._effectiveTarget = target;
  53763. return _this;
  53764. }
  53765. SwitchBooleanAction.prototype._prepare = function () {
  53766. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53767. this._property = this._getProperty(this.propertyPath);
  53768. };
  53769. SwitchBooleanAction.prototype.execute = function () {
  53770. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53771. };
  53772. SwitchBooleanAction.prototype.serialize = function (parent) {
  53773. return _super.prototype._serialize.call(this, {
  53774. name: "SwitchBooleanAction",
  53775. properties: [
  53776. BABYLON.Action._GetTargetProperty(this._target),
  53777. { name: "propertyPath", value: this.propertyPath }
  53778. ]
  53779. }, parent);
  53780. };
  53781. return SwitchBooleanAction;
  53782. }(BABYLON.Action));
  53783. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53784. var SetStateAction = /** @class */ (function (_super) {
  53785. __extends(SetStateAction, _super);
  53786. function SetStateAction(triggerOptions, target, value, condition) {
  53787. var _this = _super.call(this, triggerOptions, condition) || this;
  53788. _this.value = value;
  53789. _this._target = target;
  53790. return _this;
  53791. }
  53792. SetStateAction.prototype.execute = function () {
  53793. this._target.state = this.value;
  53794. };
  53795. SetStateAction.prototype.serialize = function (parent) {
  53796. return _super.prototype._serialize.call(this, {
  53797. name: "SetStateAction",
  53798. properties: [
  53799. BABYLON.Action._GetTargetProperty(this._target),
  53800. { name: "value", value: this.value }
  53801. ]
  53802. }, parent);
  53803. };
  53804. return SetStateAction;
  53805. }(BABYLON.Action));
  53806. BABYLON.SetStateAction = SetStateAction;
  53807. var SetValueAction = /** @class */ (function (_super) {
  53808. __extends(SetValueAction, _super);
  53809. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53810. var _this = _super.call(this, triggerOptions, condition) || this;
  53811. _this.propertyPath = propertyPath;
  53812. _this.value = value;
  53813. _this._target = _this._effectiveTarget = target;
  53814. return _this;
  53815. }
  53816. SetValueAction.prototype._prepare = function () {
  53817. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53818. this._property = this._getProperty(this.propertyPath);
  53819. };
  53820. SetValueAction.prototype.execute = function () {
  53821. this._effectiveTarget[this._property] = this.value;
  53822. if (this._target.markAsDirty) {
  53823. this._target.markAsDirty(this._property);
  53824. }
  53825. };
  53826. SetValueAction.prototype.serialize = function (parent) {
  53827. return _super.prototype._serialize.call(this, {
  53828. name: "SetValueAction",
  53829. properties: [
  53830. BABYLON.Action._GetTargetProperty(this._target),
  53831. { name: "propertyPath", value: this.propertyPath },
  53832. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53833. ]
  53834. }, parent);
  53835. };
  53836. return SetValueAction;
  53837. }(BABYLON.Action));
  53838. BABYLON.SetValueAction = SetValueAction;
  53839. var IncrementValueAction = /** @class */ (function (_super) {
  53840. __extends(IncrementValueAction, _super);
  53841. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53842. var _this = _super.call(this, triggerOptions, condition) || this;
  53843. _this.propertyPath = propertyPath;
  53844. _this.value = value;
  53845. _this._target = _this._effectiveTarget = target;
  53846. return _this;
  53847. }
  53848. IncrementValueAction.prototype._prepare = function () {
  53849. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53850. this._property = this._getProperty(this.propertyPath);
  53851. if (typeof this._effectiveTarget[this._property] !== "number") {
  53852. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53853. }
  53854. };
  53855. IncrementValueAction.prototype.execute = function () {
  53856. this._effectiveTarget[this._property] += this.value;
  53857. if (this._target.markAsDirty) {
  53858. this._target.markAsDirty(this._property);
  53859. }
  53860. };
  53861. IncrementValueAction.prototype.serialize = function (parent) {
  53862. return _super.prototype._serialize.call(this, {
  53863. name: "IncrementValueAction",
  53864. properties: [
  53865. BABYLON.Action._GetTargetProperty(this._target),
  53866. { name: "propertyPath", value: this.propertyPath },
  53867. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53868. ]
  53869. }, parent);
  53870. };
  53871. return IncrementValueAction;
  53872. }(BABYLON.Action));
  53873. BABYLON.IncrementValueAction = IncrementValueAction;
  53874. var PlayAnimationAction = /** @class */ (function (_super) {
  53875. __extends(PlayAnimationAction, _super);
  53876. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53877. var _this = _super.call(this, triggerOptions, condition) || this;
  53878. _this.from = from;
  53879. _this.to = to;
  53880. _this.loop = loop;
  53881. _this._target = target;
  53882. return _this;
  53883. }
  53884. PlayAnimationAction.prototype._prepare = function () {
  53885. };
  53886. PlayAnimationAction.prototype.execute = function () {
  53887. var scene = this._actionManager.getScene();
  53888. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53889. };
  53890. PlayAnimationAction.prototype.serialize = function (parent) {
  53891. return _super.prototype._serialize.call(this, {
  53892. name: "PlayAnimationAction",
  53893. properties: [
  53894. BABYLON.Action._GetTargetProperty(this._target),
  53895. { name: "from", value: String(this.from) },
  53896. { name: "to", value: String(this.to) },
  53897. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53898. ]
  53899. }, parent);
  53900. };
  53901. return PlayAnimationAction;
  53902. }(BABYLON.Action));
  53903. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53904. var StopAnimationAction = /** @class */ (function (_super) {
  53905. __extends(StopAnimationAction, _super);
  53906. function StopAnimationAction(triggerOptions, target, condition) {
  53907. var _this = _super.call(this, triggerOptions, condition) || this;
  53908. _this._target = target;
  53909. return _this;
  53910. }
  53911. StopAnimationAction.prototype._prepare = function () {
  53912. };
  53913. StopAnimationAction.prototype.execute = function () {
  53914. var scene = this._actionManager.getScene();
  53915. scene.stopAnimation(this._target);
  53916. };
  53917. StopAnimationAction.prototype.serialize = function (parent) {
  53918. return _super.prototype._serialize.call(this, {
  53919. name: "StopAnimationAction",
  53920. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53921. }, parent);
  53922. };
  53923. return StopAnimationAction;
  53924. }(BABYLON.Action));
  53925. BABYLON.StopAnimationAction = StopAnimationAction;
  53926. var DoNothingAction = /** @class */ (function (_super) {
  53927. __extends(DoNothingAction, _super);
  53928. function DoNothingAction(triggerOptions, condition) {
  53929. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53930. return _super.call(this, triggerOptions, condition) || this;
  53931. }
  53932. DoNothingAction.prototype.execute = function () {
  53933. };
  53934. DoNothingAction.prototype.serialize = function (parent) {
  53935. return _super.prototype._serialize.call(this, {
  53936. name: "DoNothingAction",
  53937. properties: []
  53938. }, parent);
  53939. };
  53940. return DoNothingAction;
  53941. }(BABYLON.Action));
  53942. BABYLON.DoNothingAction = DoNothingAction;
  53943. var CombineAction = /** @class */ (function (_super) {
  53944. __extends(CombineAction, _super);
  53945. function CombineAction(triggerOptions, children, condition) {
  53946. var _this = _super.call(this, triggerOptions, condition) || this;
  53947. _this.children = children;
  53948. return _this;
  53949. }
  53950. CombineAction.prototype._prepare = function () {
  53951. for (var index = 0; index < this.children.length; index++) {
  53952. this.children[index]._actionManager = this._actionManager;
  53953. this.children[index]._prepare();
  53954. }
  53955. };
  53956. CombineAction.prototype.execute = function (evt) {
  53957. for (var index = 0; index < this.children.length; index++) {
  53958. this.children[index].execute(evt);
  53959. }
  53960. };
  53961. CombineAction.prototype.serialize = function (parent) {
  53962. var serializationObject = _super.prototype._serialize.call(this, {
  53963. name: "CombineAction",
  53964. properties: [],
  53965. combine: []
  53966. }, parent);
  53967. for (var i = 0; i < this.children.length; i++) {
  53968. serializationObject.combine.push(this.children[i].serialize(null));
  53969. }
  53970. return serializationObject;
  53971. };
  53972. return CombineAction;
  53973. }(BABYLON.Action));
  53974. BABYLON.CombineAction = CombineAction;
  53975. var ExecuteCodeAction = /** @class */ (function (_super) {
  53976. __extends(ExecuteCodeAction, _super);
  53977. function ExecuteCodeAction(triggerOptions, func, condition) {
  53978. var _this = _super.call(this, triggerOptions, condition) || this;
  53979. _this.func = func;
  53980. return _this;
  53981. }
  53982. ExecuteCodeAction.prototype.execute = function (evt) {
  53983. this.func(evt);
  53984. };
  53985. return ExecuteCodeAction;
  53986. }(BABYLON.Action));
  53987. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53988. var SetParentAction = /** @class */ (function (_super) {
  53989. __extends(SetParentAction, _super);
  53990. function SetParentAction(triggerOptions, target, parent, condition) {
  53991. var _this = _super.call(this, triggerOptions, condition) || this;
  53992. _this._target = target;
  53993. _this._parent = parent;
  53994. return _this;
  53995. }
  53996. SetParentAction.prototype._prepare = function () {
  53997. };
  53998. SetParentAction.prototype.execute = function () {
  53999. if (this._target.parent === this._parent) {
  54000. return;
  54001. }
  54002. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54003. invertParentWorldMatrix.invert();
  54004. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54005. this._target.parent = this._parent;
  54006. };
  54007. SetParentAction.prototype.serialize = function (parent) {
  54008. return _super.prototype._serialize.call(this, {
  54009. name: "SetParentAction",
  54010. properties: [
  54011. BABYLON.Action._GetTargetProperty(this._target),
  54012. BABYLON.Action._GetTargetProperty(this._parent),
  54013. ]
  54014. }, parent);
  54015. };
  54016. return SetParentAction;
  54017. }(BABYLON.Action));
  54018. BABYLON.SetParentAction = SetParentAction;
  54019. var PlaySoundAction = /** @class */ (function (_super) {
  54020. __extends(PlaySoundAction, _super);
  54021. function PlaySoundAction(triggerOptions, sound, condition) {
  54022. var _this = _super.call(this, triggerOptions, condition) || this;
  54023. _this._sound = sound;
  54024. return _this;
  54025. }
  54026. PlaySoundAction.prototype._prepare = function () {
  54027. };
  54028. PlaySoundAction.prototype.execute = function () {
  54029. if (this._sound !== undefined)
  54030. this._sound.play();
  54031. };
  54032. PlaySoundAction.prototype.serialize = function (parent) {
  54033. return _super.prototype._serialize.call(this, {
  54034. name: "PlaySoundAction",
  54035. properties: [{ name: "sound", value: this._sound.name }]
  54036. }, parent);
  54037. };
  54038. return PlaySoundAction;
  54039. }(BABYLON.Action));
  54040. BABYLON.PlaySoundAction = PlaySoundAction;
  54041. var StopSoundAction = /** @class */ (function (_super) {
  54042. __extends(StopSoundAction, _super);
  54043. function StopSoundAction(triggerOptions, sound, condition) {
  54044. var _this = _super.call(this, triggerOptions, condition) || this;
  54045. _this._sound = sound;
  54046. return _this;
  54047. }
  54048. StopSoundAction.prototype._prepare = function () {
  54049. };
  54050. StopSoundAction.prototype.execute = function () {
  54051. if (this._sound !== undefined)
  54052. this._sound.stop();
  54053. };
  54054. StopSoundAction.prototype.serialize = function (parent) {
  54055. return _super.prototype._serialize.call(this, {
  54056. name: "StopSoundAction",
  54057. properties: [{ name: "sound", value: this._sound.name }]
  54058. }, parent);
  54059. };
  54060. return StopSoundAction;
  54061. }(BABYLON.Action));
  54062. BABYLON.StopSoundAction = StopSoundAction;
  54063. })(BABYLON || (BABYLON = {}));
  54064. //# sourceMappingURL=babylon.directActions.js.map
  54065. var BABYLON;
  54066. (function (BABYLON) {
  54067. var SpriteManager = /** @class */ (function () {
  54068. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54069. if (epsilon === void 0) { epsilon = 0.01; }
  54070. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54071. this.name = name;
  54072. this.sprites = new Array();
  54073. this.renderingGroupId = 0;
  54074. this.layerMask = 0x0FFFFFFF;
  54075. this.fogEnabled = true;
  54076. this.isPickable = false;
  54077. /**
  54078. * An event triggered when the manager is disposed.
  54079. */
  54080. this.onDisposeObservable = new BABYLON.Observable();
  54081. this._vertexBuffers = {};
  54082. this._capacity = capacity;
  54083. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54084. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54085. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54086. if (cellSize.width && cellSize.height) {
  54087. this.cellWidth = cellSize.width;
  54088. this.cellHeight = cellSize.height;
  54089. }
  54090. else if (cellSize !== undefined) {
  54091. this.cellWidth = cellSize;
  54092. this.cellHeight = cellSize;
  54093. }
  54094. else {
  54095. return;
  54096. }
  54097. this._epsilon = epsilon;
  54098. this._scene = scene;
  54099. this._scene.spriteManagers.push(this);
  54100. var indices = [];
  54101. var index = 0;
  54102. for (var count = 0; count < capacity; count++) {
  54103. indices.push(index);
  54104. indices.push(index + 1);
  54105. indices.push(index + 2);
  54106. indices.push(index);
  54107. indices.push(index + 2);
  54108. indices.push(index + 3);
  54109. index += 4;
  54110. }
  54111. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54112. // VBO
  54113. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54114. this._vertexData = new Float32Array(capacity * 16 * 4);
  54115. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54116. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54117. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54118. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54119. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54120. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54121. this._vertexBuffers["options"] = options;
  54122. this._vertexBuffers["cellInfo"] = cellInfo;
  54123. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54124. // Effects
  54125. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54126. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54127. }
  54128. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54129. set: function (callback) {
  54130. if (this._onDisposeObserver) {
  54131. this.onDisposeObservable.remove(this._onDisposeObserver);
  54132. }
  54133. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54134. },
  54135. enumerable: true,
  54136. configurable: true
  54137. });
  54138. Object.defineProperty(SpriteManager.prototype, "texture", {
  54139. get: function () {
  54140. return this._spriteTexture;
  54141. },
  54142. set: function (value) {
  54143. this._spriteTexture = value;
  54144. },
  54145. enumerable: true,
  54146. configurable: true
  54147. });
  54148. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54149. var arrayOffset = index * 16;
  54150. if (offsetX === 0)
  54151. offsetX = this._epsilon;
  54152. else if (offsetX === 1)
  54153. offsetX = 1 - this._epsilon;
  54154. if (offsetY === 0)
  54155. offsetY = this._epsilon;
  54156. else if (offsetY === 1)
  54157. offsetY = 1 - this._epsilon;
  54158. this._vertexData[arrayOffset] = sprite.position.x;
  54159. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54160. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54161. this._vertexData[arrayOffset + 3] = sprite.angle;
  54162. this._vertexData[arrayOffset + 4] = sprite.width;
  54163. this._vertexData[arrayOffset + 5] = sprite.height;
  54164. this._vertexData[arrayOffset + 6] = offsetX;
  54165. this._vertexData[arrayOffset + 7] = offsetY;
  54166. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54167. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54168. var offset = (sprite.cellIndex / rowSize) >> 0;
  54169. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54170. this._vertexData[arrayOffset + 11] = offset;
  54171. // Color
  54172. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54173. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54174. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54175. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54176. };
  54177. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54178. var count = Math.min(this._capacity, this.sprites.length);
  54179. var min = BABYLON.Vector3.Zero();
  54180. var max = BABYLON.Vector3.Zero();
  54181. var distance = Number.MAX_VALUE;
  54182. var currentSprite = null;
  54183. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54184. var cameraView = camera.getViewMatrix();
  54185. for (var index = 0; index < count; index++) {
  54186. var sprite = this.sprites[index];
  54187. if (!sprite) {
  54188. continue;
  54189. }
  54190. if (predicate) {
  54191. if (!predicate(sprite)) {
  54192. continue;
  54193. }
  54194. }
  54195. else if (!sprite.isPickable) {
  54196. continue;
  54197. }
  54198. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54199. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54200. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54201. if (ray.intersectsBoxMinMax(min, max)) {
  54202. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54203. if (distance > currentDistance) {
  54204. distance = currentDistance;
  54205. currentSprite = sprite;
  54206. if (fastCheck) {
  54207. break;
  54208. }
  54209. }
  54210. }
  54211. }
  54212. if (currentSprite) {
  54213. var result = new BABYLON.PickingInfo();
  54214. result.hit = true;
  54215. result.pickedSprite = currentSprite;
  54216. result.distance = distance;
  54217. return result;
  54218. }
  54219. return null;
  54220. };
  54221. SpriteManager.prototype.render = function () {
  54222. // Check
  54223. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54224. return;
  54225. var engine = this._scene.getEngine();
  54226. var baseSize = this._spriteTexture.getBaseSize();
  54227. // Sprites
  54228. var deltaTime = engine.getDeltaTime();
  54229. var max = Math.min(this._capacity, this.sprites.length);
  54230. var rowSize = baseSize.width / this.cellWidth;
  54231. var offset = 0;
  54232. for (var index = 0; index < max; index++) {
  54233. var sprite = this.sprites[index];
  54234. if (!sprite) {
  54235. continue;
  54236. }
  54237. sprite._animate(deltaTime);
  54238. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54239. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54240. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54241. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54242. }
  54243. this._buffer.update(this._vertexData);
  54244. // Render
  54245. var effect = this._effectBase;
  54246. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54247. effect = this._effectFog;
  54248. }
  54249. engine.enableEffect(effect);
  54250. var viewMatrix = this._scene.getViewMatrix();
  54251. effect.setTexture("diffuseSampler", this._spriteTexture);
  54252. effect.setMatrix("view", viewMatrix);
  54253. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54254. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54255. // Fog
  54256. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54257. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54258. effect.setColor3("vFogColor", this._scene.fogColor);
  54259. }
  54260. // VBOs
  54261. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54262. // Draw order
  54263. engine.setDepthFunctionToLessOrEqual();
  54264. effect.setBool("alphaTest", true);
  54265. engine.setColorWrite(false);
  54266. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54267. engine.setColorWrite(true);
  54268. effect.setBool("alphaTest", false);
  54269. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54270. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54271. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54272. };
  54273. SpriteManager.prototype.dispose = function () {
  54274. if (this._buffer) {
  54275. this._buffer.dispose();
  54276. this._buffer = null;
  54277. }
  54278. if (this._indexBuffer) {
  54279. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54280. this._indexBuffer = null;
  54281. }
  54282. if (this._spriteTexture) {
  54283. this._spriteTexture.dispose();
  54284. this._spriteTexture = null;
  54285. }
  54286. // Remove from scene
  54287. var index = this._scene.spriteManagers.indexOf(this);
  54288. this._scene.spriteManagers.splice(index, 1);
  54289. // Callback
  54290. this.onDisposeObservable.notifyObservers(this);
  54291. this.onDisposeObservable.clear();
  54292. };
  54293. return SpriteManager;
  54294. }());
  54295. BABYLON.SpriteManager = SpriteManager;
  54296. })(BABYLON || (BABYLON = {}));
  54297. //# sourceMappingURL=babylon.spriteManager.js.map
  54298. var BABYLON;
  54299. (function (BABYLON) {
  54300. var Sprite = /** @class */ (function () {
  54301. function Sprite(name, manager) {
  54302. this.name = name;
  54303. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54304. this.width = 1.0;
  54305. this.height = 1.0;
  54306. this.angle = 0;
  54307. this.cellIndex = 0;
  54308. this.invertU = 0;
  54309. this.invertV = 0;
  54310. this.animations = new Array();
  54311. this.isPickable = false;
  54312. this._animationStarted = false;
  54313. this._loopAnimation = false;
  54314. this._fromIndex = 0;
  54315. this._toIndex = 0;
  54316. this._delay = 0;
  54317. this._direction = 1;
  54318. this._time = 0;
  54319. this._manager = manager;
  54320. this._manager.sprites.push(this);
  54321. this.position = BABYLON.Vector3.Zero();
  54322. }
  54323. Object.defineProperty(Sprite.prototype, "size", {
  54324. get: function () {
  54325. return this.width;
  54326. },
  54327. set: function (value) {
  54328. this.width = value;
  54329. this.height = value;
  54330. },
  54331. enumerable: true,
  54332. configurable: true
  54333. });
  54334. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54335. this._fromIndex = from;
  54336. this._toIndex = to;
  54337. this._loopAnimation = loop;
  54338. this._delay = delay;
  54339. this._animationStarted = true;
  54340. this._direction = from < to ? 1 : -1;
  54341. this.cellIndex = from;
  54342. this._time = 0;
  54343. this._onAnimationEnd = onAnimationEnd;
  54344. };
  54345. Sprite.prototype.stopAnimation = function () {
  54346. this._animationStarted = false;
  54347. };
  54348. Sprite.prototype._animate = function (deltaTime) {
  54349. if (!this._animationStarted)
  54350. return;
  54351. this._time += deltaTime;
  54352. if (this._time > this._delay) {
  54353. this._time = this._time % this._delay;
  54354. this.cellIndex += this._direction;
  54355. if (this.cellIndex > this._toIndex) {
  54356. if (this._loopAnimation) {
  54357. this.cellIndex = this._fromIndex;
  54358. }
  54359. else {
  54360. this.cellIndex = this._toIndex;
  54361. this._animationStarted = false;
  54362. if (this._onAnimationEnd) {
  54363. this._onAnimationEnd();
  54364. }
  54365. if (this.disposeWhenFinishedAnimating) {
  54366. this.dispose();
  54367. }
  54368. }
  54369. }
  54370. }
  54371. };
  54372. Sprite.prototype.dispose = function () {
  54373. for (var i = 0; i < this._manager.sprites.length; i++) {
  54374. if (this._manager.sprites[i] == this) {
  54375. this._manager.sprites.splice(i, 1);
  54376. }
  54377. }
  54378. };
  54379. return Sprite;
  54380. }());
  54381. BABYLON.Sprite = Sprite;
  54382. })(BABYLON || (BABYLON = {}));
  54383. //# sourceMappingURL=babylon.sprite.js.map
  54384. var BABYLON;
  54385. (function (BABYLON) {
  54386. var IntersectionInfo = /** @class */ (function () {
  54387. function IntersectionInfo(bu, bv, distance) {
  54388. this.bu = bu;
  54389. this.bv = bv;
  54390. this.distance = distance;
  54391. this.faceId = 0;
  54392. this.subMeshId = 0;
  54393. }
  54394. return IntersectionInfo;
  54395. }());
  54396. BABYLON.IntersectionInfo = IntersectionInfo;
  54397. var PickingInfo = /** @class */ (function () {
  54398. function PickingInfo() {
  54399. this.hit = false;
  54400. this.distance = 0;
  54401. this.pickedPoint = null;
  54402. this.pickedMesh = null;
  54403. this.bu = 0;
  54404. this.bv = 0;
  54405. this.faceId = -1;
  54406. this.subMeshId = 0;
  54407. this.pickedSprite = null;
  54408. }
  54409. // Methods
  54410. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54411. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54412. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54413. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54414. return null;
  54415. }
  54416. var indices = this.pickedMesh.getIndices();
  54417. if (!indices) {
  54418. return null;
  54419. }
  54420. var result;
  54421. if (useVerticesNormals) {
  54422. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54423. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54424. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54425. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54426. normal0 = normal0.scale(this.bu);
  54427. normal1 = normal1.scale(this.bv);
  54428. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54429. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54430. }
  54431. else {
  54432. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54433. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54434. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54435. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54436. var p1p2 = vertex1.subtract(vertex2);
  54437. var p3p2 = vertex3.subtract(vertex2);
  54438. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54439. }
  54440. if (useWorldCoordinates) {
  54441. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54442. }
  54443. return BABYLON.Vector3.Normalize(result);
  54444. };
  54445. PickingInfo.prototype.getTextureCoordinates = function () {
  54446. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54447. return null;
  54448. }
  54449. var indices = this.pickedMesh.getIndices();
  54450. if (!indices) {
  54451. return null;
  54452. }
  54453. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54454. if (!uvs) {
  54455. return null;
  54456. }
  54457. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54458. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54459. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54460. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54461. uv1 = uv1.scale(this.bu);
  54462. uv2 = uv2.scale(this.bv);
  54463. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54464. };
  54465. return PickingInfo;
  54466. }());
  54467. BABYLON.PickingInfo = PickingInfo;
  54468. })(BABYLON || (BABYLON = {}));
  54469. //# sourceMappingURL=babylon.pickingInfo.js.map
  54470. var BABYLON;
  54471. (function (BABYLON) {
  54472. var Ray = /** @class */ (function () {
  54473. function Ray(origin, direction, length) {
  54474. if (length === void 0) { length = Number.MAX_VALUE; }
  54475. this.origin = origin;
  54476. this.direction = direction;
  54477. this.length = length;
  54478. }
  54479. // Methods
  54480. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54481. var d = 0.0;
  54482. var maxValue = Number.MAX_VALUE;
  54483. var inv;
  54484. var min;
  54485. var max;
  54486. var temp;
  54487. if (Math.abs(this.direction.x) < 0.0000001) {
  54488. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54489. return false;
  54490. }
  54491. }
  54492. else {
  54493. inv = 1.0 / this.direction.x;
  54494. min = (minimum.x - this.origin.x) * inv;
  54495. max = (maximum.x - this.origin.x) * inv;
  54496. if (max === -Infinity) {
  54497. max = Infinity;
  54498. }
  54499. if (min > max) {
  54500. temp = min;
  54501. min = max;
  54502. max = temp;
  54503. }
  54504. d = Math.max(min, d);
  54505. maxValue = Math.min(max, maxValue);
  54506. if (d > maxValue) {
  54507. return false;
  54508. }
  54509. }
  54510. if (Math.abs(this.direction.y) < 0.0000001) {
  54511. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54512. return false;
  54513. }
  54514. }
  54515. else {
  54516. inv = 1.0 / this.direction.y;
  54517. min = (minimum.y - this.origin.y) * inv;
  54518. max = (maximum.y - this.origin.y) * inv;
  54519. if (max === -Infinity) {
  54520. max = Infinity;
  54521. }
  54522. if (min > max) {
  54523. temp = min;
  54524. min = max;
  54525. max = temp;
  54526. }
  54527. d = Math.max(min, d);
  54528. maxValue = Math.min(max, maxValue);
  54529. if (d > maxValue) {
  54530. return false;
  54531. }
  54532. }
  54533. if (Math.abs(this.direction.z) < 0.0000001) {
  54534. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54535. return false;
  54536. }
  54537. }
  54538. else {
  54539. inv = 1.0 / this.direction.z;
  54540. min = (minimum.z - this.origin.z) * inv;
  54541. max = (maximum.z - this.origin.z) * inv;
  54542. if (max === -Infinity) {
  54543. max = Infinity;
  54544. }
  54545. if (min > max) {
  54546. temp = min;
  54547. min = max;
  54548. max = temp;
  54549. }
  54550. d = Math.max(min, d);
  54551. maxValue = Math.min(max, maxValue);
  54552. if (d > maxValue) {
  54553. return false;
  54554. }
  54555. }
  54556. return true;
  54557. };
  54558. Ray.prototype.intersectsBox = function (box) {
  54559. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54560. };
  54561. Ray.prototype.intersectsSphere = function (sphere) {
  54562. var x = sphere.center.x - this.origin.x;
  54563. var y = sphere.center.y - this.origin.y;
  54564. var z = sphere.center.z - this.origin.z;
  54565. var pyth = (x * x) + (y * y) + (z * z);
  54566. var rr = sphere.radius * sphere.radius;
  54567. if (pyth <= rr) {
  54568. return true;
  54569. }
  54570. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54571. if (dot < 0.0) {
  54572. return false;
  54573. }
  54574. var temp = pyth - (dot * dot);
  54575. return temp <= rr;
  54576. };
  54577. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54578. if (!this._edge1) {
  54579. this._edge1 = BABYLON.Vector3.Zero();
  54580. this._edge2 = BABYLON.Vector3.Zero();
  54581. this._pvec = BABYLON.Vector3.Zero();
  54582. this._tvec = BABYLON.Vector3.Zero();
  54583. this._qvec = BABYLON.Vector3.Zero();
  54584. }
  54585. vertex1.subtractToRef(vertex0, this._edge1);
  54586. vertex2.subtractToRef(vertex0, this._edge2);
  54587. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54588. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54589. if (det === 0) {
  54590. return null;
  54591. }
  54592. var invdet = 1 / det;
  54593. this.origin.subtractToRef(vertex0, this._tvec);
  54594. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54595. if (bu < 0 || bu > 1.0) {
  54596. return null;
  54597. }
  54598. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54599. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54600. if (bv < 0 || bu + bv > 1.0) {
  54601. return null;
  54602. }
  54603. //check if the distance is longer than the predefined length.
  54604. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54605. if (distance > this.length) {
  54606. return null;
  54607. }
  54608. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54609. };
  54610. Ray.prototype.intersectsPlane = function (plane) {
  54611. var distance;
  54612. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54613. if (Math.abs(result1) < 9.99999997475243E-07) {
  54614. return null;
  54615. }
  54616. else {
  54617. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54618. distance = (-plane.d - result2) / result1;
  54619. if (distance < 0.0) {
  54620. if (distance < -9.99999997475243E-07) {
  54621. return null;
  54622. }
  54623. else {
  54624. return 0;
  54625. }
  54626. }
  54627. return distance;
  54628. }
  54629. };
  54630. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54631. var tm = BABYLON.Tmp.Matrix[0];
  54632. mesh.getWorldMatrix().invertToRef(tm);
  54633. if (this._tmpRay) {
  54634. Ray.TransformToRef(this, tm, this._tmpRay);
  54635. }
  54636. else {
  54637. this._tmpRay = Ray.Transform(this, tm);
  54638. }
  54639. return mesh.intersects(this._tmpRay, fastCheck);
  54640. };
  54641. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54642. if (results) {
  54643. results.length = 0;
  54644. }
  54645. else {
  54646. results = [];
  54647. }
  54648. for (var i = 0; i < meshes.length; i++) {
  54649. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54650. if (pickInfo.hit) {
  54651. results.push(pickInfo);
  54652. }
  54653. }
  54654. results.sort(this._comparePickingInfo);
  54655. return results;
  54656. };
  54657. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54658. if (pickingInfoA.distance < pickingInfoB.distance) {
  54659. return -1;
  54660. }
  54661. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54662. return 1;
  54663. }
  54664. else {
  54665. return 0;
  54666. }
  54667. };
  54668. /**
  54669. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54670. * @param sega the first point of the segment to test the intersection against
  54671. * @param segb the second point of the segment to test the intersection against
  54672. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54673. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54674. */
  54675. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54676. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54677. var u = segb.subtract(sega);
  54678. var v = rsegb.subtract(this.origin);
  54679. var w = sega.subtract(this.origin);
  54680. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54681. var b = BABYLON.Vector3.Dot(u, v);
  54682. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54683. var d = BABYLON.Vector3.Dot(u, w);
  54684. var e = BABYLON.Vector3.Dot(v, w);
  54685. var D = a * c - b * b; // always >= 0
  54686. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54687. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54688. // compute the line parameters of the two closest points
  54689. if (D < Ray.smallnum) { // the lines are almost parallel
  54690. sN = 0.0; // force using point P0 on segment S1
  54691. sD = 1.0; // to prevent possible division by 0.0 later
  54692. tN = e;
  54693. tD = c;
  54694. }
  54695. else { // get the closest points on the infinite lines
  54696. sN = (b * e - c * d);
  54697. tN = (a * e - b * d);
  54698. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54699. sN = 0.0;
  54700. tN = e;
  54701. tD = c;
  54702. }
  54703. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54704. sN = sD;
  54705. tN = e + b;
  54706. tD = c;
  54707. }
  54708. }
  54709. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54710. tN = 0.0;
  54711. // recompute sc for this edge
  54712. if (-d < 0.0) {
  54713. sN = 0.0;
  54714. }
  54715. else if (-d > a)
  54716. sN = sD;
  54717. else {
  54718. sN = -d;
  54719. sD = a;
  54720. }
  54721. }
  54722. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54723. tN = tD;
  54724. // recompute sc for this edge
  54725. if ((-d + b) < 0.0) {
  54726. sN = 0;
  54727. }
  54728. else if ((-d + b) > a) {
  54729. sN = sD;
  54730. }
  54731. else {
  54732. sN = (-d + b);
  54733. sD = a;
  54734. }
  54735. }
  54736. // finally do the division to get sc and tc
  54737. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54738. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54739. // get the difference of the two closest points
  54740. var qtc = v.multiplyByFloats(tc, tc, tc);
  54741. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54742. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54743. if (isIntersected) {
  54744. return qtc.length();
  54745. }
  54746. return -1;
  54747. };
  54748. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54749. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54750. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54751. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54752. this.direction.normalize();
  54753. return this;
  54754. };
  54755. // Statics
  54756. Ray.Zero = function () {
  54757. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54758. };
  54759. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54760. var result = Ray.Zero();
  54761. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54762. };
  54763. /**
  54764. * 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
  54765. * transformed to the given world matrix.
  54766. * @param origin The origin point
  54767. * @param end The end point
  54768. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54769. */
  54770. Ray.CreateNewFromTo = function (origin, end, world) {
  54771. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54772. var direction = end.subtract(origin);
  54773. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54774. direction.normalize();
  54775. return Ray.Transform(new Ray(origin, direction, length), world);
  54776. };
  54777. Ray.Transform = function (ray, matrix) {
  54778. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54779. Ray.TransformToRef(ray, matrix, result);
  54780. return result;
  54781. };
  54782. Ray.TransformToRef = function (ray, matrix, result) {
  54783. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54784. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54785. result.length = ray.length;
  54786. var dir = result.direction;
  54787. var len = dir.length();
  54788. if (!(len === 0 || len === 1)) {
  54789. var num = 1.0 / len;
  54790. dir.x *= num;
  54791. dir.y *= num;
  54792. dir.z *= num;
  54793. result.length *= len;
  54794. }
  54795. };
  54796. Ray.smallnum = 0.00000001;
  54797. Ray.rayl = 10e8;
  54798. return Ray;
  54799. }());
  54800. BABYLON.Ray = Ray;
  54801. })(BABYLON || (BABYLON = {}));
  54802. //# sourceMappingURL=babylon.ray.js.map
  54803. var BABYLON;
  54804. (function (BABYLON) {
  54805. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54806. if (boxMin.x > sphereCenter.x + sphereRadius)
  54807. return false;
  54808. if (sphereCenter.x - sphereRadius > boxMax.x)
  54809. return false;
  54810. if (boxMin.y > sphereCenter.y + sphereRadius)
  54811. return false;
  54812. if (sphereCenter.y - sphereRadius > boxMax.y)
  54813. return false;
  54814. if (boxMin.z > sphereCenter.z + sphereRadius)
  54815. return false;
  54816. if (sphereCenter.z - sphereRadius > boxMax.z)
  54817. return false;
  54818. return true;
  54819. };
  54820. var getLowestRoot = (function () {
  54821. var result = { root: 0, found: false };
  54822. return function (a, b, c, maxR) {
  54823. result.root = 0;
  54824. result.found = false;
  54825. var determinant = b * b - 4.0 * a * c;
  54826. if (determinant < 0)
  54827. return result;
  54828. var sqrtD = Math.sqrt(determinant);
  54829. var r1 = (-b - sqrtD) / (2.0 * a);
  54830. var r2 = (-b + sqrtD) / (2.0 * a);
  54831. if (r1 > r2) {
  54832. var temp = r2;
  54833. r2 = r1;
  54834. r1 = temp;
  54835. }
  54836. if (r1 > 0 && r1 < maxR) {
  54837. result.root = r1;
  54838. result.found = true;
  54839. return result;
  54840. }
  54841. if (r2 > 0 && r2 < maxR) {
  54842. result.root = r2;
  54843. result.found = true;
  54844. return result;
  54845. }
  54846. return result;
  54847. };
  54848. })();
  54849. var Collider = /** @class */ (function () {
  54850. function Collider() {
  54851. this._collisionPoint = BABYLON.Vector3.Zero();
  54852. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54853. this._tempVector = BABYLON.Vector3.Zero();
  54854. this._tempVector2 = BABYLON.Vector3.Zero();
  54855. this._tempVector3 = BABYLON.Vector3.Zero();
  54856. this._tempVector4 = BABYLON.Vector3.Zero();
  54857. this._edge = BABYLON.Vector3.Zero();
  54858. this._baseToVertex = BABYLON.Vector3.Zero();
  54859. this._destinationPoint = BABYLON.Vector3.Zero();
  54860. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54861. this._displacementVector = BABYLON.Vector3.Zero();
  54862. this._radius = BABYLON.Vector3.One();
  54863. this._retry = 0;
  54864. this._basePointWorld = BABYLON.Vector3.Zero();
  54865. this._velocityWorld = BABYLON.Vector3.Zero();
  54866. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54867. this._collisionMask = -1;
  54868. }
  54869. Object.defineProperty(Collider.prototype, "collisionMask", {
  54870. get: function () {
  54871. return this._collisionMask;
  54872. },
  54873. set: function (mask) {
  54874. this._collisionMask = !isNaN(mask) ? mask : -1;
  54875. },
  54876. enumerable: true,
  54877. configurable: true
  54878. });
  54879. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54880. /**
  54881. * Gets the plane normal used to compute the sliding response (in local space)
  54882. */
  54883. get: function () {
  54884. return this._slidePlaneNormal;
  54885. },
  54886. enumerable: true,
  54887. configurable: true
  54888. });
  54889. // Methods
  54890. Collider.prototype._initialize = function (source, dir, e) {
  54891. this._velocity = dir;
  54892. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54893. this._basePoint = source;
  54894. source.multiplyToRef(this._radius, this._basePointWorld);
  54895. dir.multiplyToRef(this._radius, this._velocityWorld);
  54896. this._velocityWorldLength = this._velocityWorld.length();
  54897. this._epsilon = e;
  54898. this.collisionFound = false;
  54899. };
  54900. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54901. pa.subtractToRef(point, this._tempVector);
  54902. pb.subtractToRef(point, this._tempVector2);
  54903. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54904. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54905. if (d < 0)
  54906. return false;
  54907. pc.subtractToRef(point, this._tempVector3);
  54908. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54909. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54910. if (d < 0)
  54911. return false;
  54912. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54913. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54914. return d >= 0;
  54915. };
  54916. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54917. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54918. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54919. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54920. return false;
  54921. }
  54922. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54923. return false;
  54924. return true;
  54925. };
  54926. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54927. var t0;
  54928. var embeddedInPlane = false;
  54929. //defensive programming, actually not needed.
  54930. if (!trianglePlaneArray) {
  54931. trianglePlaneArray = [];
  54932. }
  54933. if (!trianglePlaneArray[faceIndex]) {
  54934. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54935. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54936. }
  54937. var trianglePlane = trianglePlaneArray[faceIndex];
  54938. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54939. return;
  54940. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54941. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54942. if (normalDotVelocity == 0) {
  54943. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54944. return;
  54945. embeddedInPlane = true;
  54946. t0 = 0;
  54947. }
  54948. else {
  54949. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54950. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54951. if (t0 > t1) {
  54952. var temp = t1;
  54953. t1 = t0;
  54954. t0 = temp;
  54955. }
  54956. if (t0 > 1.0 || t1 < 0.0)
  54957. return;
  54958. if (t0 < 0)
  54959. t0 = 0;
  54960. if (t0 > 1.0)
  54961. t0 = 1.0;
  54962. }
  54963. this._collisionPoint.copyFromFloats(0, 0, 0);
  54964. var found = false;
  54965. var t = 1.0;
  54966. if (!embeddedInPlane) {
  54967. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54968. this._velocity.scaleToRef(t0, this._tempVector);
  54969. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54970. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54971. found = true;
  54972. t = t0;
  54973. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54974. }
  54975. }
  54976. if (!found) {
  54977. var velocitySquaredLength = this._velocity.lengthSquared();
  54978. var a = velocitySquaredLength;
  54979. this._basePoint.subtractToRef(p1, this._tempVector);
  54980. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54981. var c = this._tempVector.lengthSquared() - 1.0;
  54982. var lowestRoot = getLowestRoot(a, b, c, t);
  54983. if (lowestRoot.found) {
  54984. t = lowestRoot.root;
  54985. found = true;
  54986. this._collisionPoint.copyFrom(p1);
  54987. }
  54988. this._basePoint.subtractToRef(p2, this._tempVector);
  54989. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54990. c = this._tempVector.lengthSquared() - 1.0;
  54991. lowestRoot = getLowestRoot(a, b, c, t);
  54992. if (lowestRoot.found) {
  54993. t = lowestRoot.root;
  54994. found = true;
  54995. this._collisionPoint.copyFrom(p2);
  54996. }
  54997. this._basePoint.subtractToRef(p3, this._tempVector);
  54998. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54999. c = this._tempVector.lengthSquared() - 1.0;
  55000. lowestRoot = getLowestRoot(a, b, c, t);
  55001. if (lowestRoot.found) {
  55002. t = lowestRoot.root;
  55003. found = true;
  55004. this._collisionPoint.copyFrom(p3);
  55005. }
  55006. p2.subtractToRef(p1, this._edge);
  55007. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55008. var edgeSquaredLength = this._edge.lengthSquared();
  55009. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55010. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55011. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55012. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55013. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55014. lowestRoot = getLowestRoot(a, b, c, t);
  55015. if (lowestRoot.found) {
  55016. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55017. if (f >= 0.0 && f <= 1.0) {
  55018. t = lowestRoot.root;
  55019. found = true;
  55020. this._edge.scaleInPlace(f);
  55021. p1.addToRef(this._edge, this._collisionPoint);
  55022. }
  55023. }
  55024. p3.subtractToRef(p2, this._edge);
  55025. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55026. edgeSquaredLength = this._edge.lengthSquared();
  55027. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55028. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55029. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55030. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55031. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55032. lowestRoot = getLowestRoot(a, b, c, t);
  55033. if (lowestRoot.found) {
  55034. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55035. if (f >= 0.0 && f <= 1.0) {
  55036. t = lowestRoot.root;
  55037. found = true;
  55038. this._edge.scaleInPlace(f);
  55039. p2.addToRef(this._edge, this._collisionPoint);
  55040. }
  55041. }
  55042. p1.subtractToRef(p3, this._edge);
  55043. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55044. edgeSquaredLength = this._edge.lengthSquared();
  55045. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55046. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55047. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55048. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55049. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55050. lowestRoot = getLowestRoot(a, b, c, t);
  55051. if (lowestRoot.found) {
  55052. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55053. if (f >= 0.0 && f <= 1.0) {
  55054. t = lowestRoot.root;
  55055. found = true;
  55056. this._edge.scaleInPlace(f);
  55057. p3.addToRef(this._edge, this._collisionPoint);
  55058. }
  55059. }
  55060. }
  55061. if (found) {
  55062. var distToCollision = t * this._velocity.length();
  55063. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55064. if (!this.intersectionPoint) {
  55065. this.intersectionPoint = this._collisionPoint.clone();
  55066. }
  55067. else {
  55068. this.intersectionPoint.copyFrom(this._collisionPoint);
  55069. }
  55070. this._nearestDistance = distToCollision;
  55071. this.collisionFound = true;
  55072. }
  55073. }
  55074. };
  55075. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55076. for (var i = indexStart; i < indexEnd; i += 3) {
  55077. var p1 = pts[indices[i] - decal];
  55078. var p2 = pts[indices[i + 1] - decal];
  55079. var p3 = pts[indices[i + 2] - decal];
  55080. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55081. }
  55082. };
  55083. Collider.prototype._getResponse = function (pos, vel) {
  55084. pos.addToRef(vel, this._destinationPoint);
  55085. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55086. this._basePoint.addToRef(vel, pos);
  55087. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55088. this._slidePlaneNormal.normalize();
  55089. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55090. pos.addInPlace(this._displacementVector);
  55091. this.intersectionPoint.addInPlace(this._displacementVector);
  55092. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55093. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55094. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55095. };
  55096. return Collider;
  55097. }());
  55098. BABYLON.Collider = Collider;
  55099. })(BABYLON || (BABYLON = {}));
  55100. //# sourceMappingURL=babylon.collider.js.map
  55101. var BABYLON;
  55102. (function (BABYLON) {
  55103. //WebWorker code will be inserted to this variable.
  55104. BABYLON.CollisionWorker = "";
  55105. /** Defines supported task for worker process */
  55106. var WorkerTaskType;
  55107. (function (WorkerTaskType) {
  55108. /** Initialization */
  55109. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55110. /** Update of geometry */
  55111. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55112. /** Evaluate collision */
  55113. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55114. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55115. /** Defines kind of replies returned by worker */
  55116. var WorkerReplyType;
  55117. (function (WorkerReplyType) {
  55118. /** Success */
  55119. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55120. /** Unkown error */
  55121. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55122. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55123. var CollisionCoordinatorWorker = /** @class */ (function () {
  55124. function CollisionCoordinatorWorker() {
  55125. var _this = this;
  55126. this._scaledPosition = BABYLON.Vector3.Zero();
  55127. this._scaledVelocity = BABYLON.Vector3.Zero();
  55128. this.onMeshUpdated = function (transformNode) {
  55129. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55130. };
  55131. this.onGeometryUpdated = function (geometry) {
  55132. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55133. };
  55134. this._afterRender = function () {
  55135. if (!_this._init)
  55136. return;
  55137. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55138. return;
  55139. }
  55140. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55141. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55142. if (_this._runningUpdated > 4) {
  55143. return;
  55144. }
  55145. ++_this._runningUpdated;
  55146. var payload = {
  55147. updatedMeshes: _this._addUpdateMeshesList,
  55148. updatedGeometries: _this._addUpdateGeometriesList,
  55149. removedGeometries: _this._toRemoveGeometryArray,
  55150. removedMeshes: _this._toRemoveMeshesArray
  55151. };
  55152. var message = {
  55153. payload: payload,
  55154. taskType: WorkerTaskType.UPDATE
  55155. };
  55156. var serializable = [];
  55157. for (var id in payload.updatedGeometries) {
  55158. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55159. //prepare transferables
  55160. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55161. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55162. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55163. }
  55164. }
  55165. _this._worker.postMessage(message, serializable);
  55166. _this._addUpdateMeshesList = {};
  55167. _this._addUpdateGeometriesList = {};
  55168. _this._toRemoveGeometryArray = [];
  55169. _this._toRemoveMeshesArray = [];
  55170. };
  55171. this._onMessageFromWorker = function (e) {
  55172. var returnData = e.data;
  55173. if (returnData.error != WorkerReplyType.SUCCESS) {
  55174. //TODO what errors can be returned from the worker?
  55175. BABYLON.Tools.Warn("error returned from worker!");
  55176. return;
  55177. }
  55178. switch (returnData.taskType) {
  55179. case WorkerTaskType.INIT:
  55180. _this._init = true;
  55181. //Update the worked with ALL of the scene's current state
  55182. _this._scene.meshes.forEach(function (mesh) {
  55183. _this.onMeshAdded(mesh);
  55184. });
  55185. _this._scene.getGeometries().forEach(function (geometry) {
  55186. _this.onGeometryAdded(geometry);
  55187. });
  55188. break;
  55189. case WorkerTaskType.UPDATE:
  55190. _this._runningUpdated--;
  55191. break;
  55192. case WorkerTaskType.COLLIDE:
  55193. var returnPayload = returnData.payload;
  55194. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55195. return;
  55196. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55197. if (callback) {
  55198. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55199. if (mesh) {
  55200. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55201. }
  55202. }
  55203. //cleanup
  55204. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55205. break;
  55206. }
  55207. };
  55208. this._collisionsCallbackArray = [];
  55209. this._init = false;
  55210. this._runningUpdated = 0;
  55211. this._addUpdateMeshesList = {};
  55212. this._addUpdateGeometriesList = {};
  55213. this._toRemoveGeometryArray = [];
  55214. this._toRemoveMeshesArray = [];
  55215. }
  55216. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55217. if (!this._init)
  55218. return;
  55219. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55220. return;
  55221. position.divideToRef(collider._radius, this._scaledPosition);
  55222. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55223. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55224. var payload = {
  55225. collider: {
  55226. position: this._scaledPosition.asArray(),
  55227. velocity: this._scaledVelocity.asArray(),
  55228. radius: collider._radius.asArray()
  55229. },
  55230. collisionId: collisionIndex,
  55231. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55232. maximumRetry: maximumRetry
  55233. };
  55234. var message = {
  55235. payload: payload,
  55236. taskType: WorkerTaskType.COLLIDE
  55237. };
  55238. this._worker.postMessage(message);
  55239. };
  55240. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55241. this._scene = scene;
  55242. this._scene.registerAfterRender(this._afterRender);
  55243. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55244. this._worker = new Worker(workerUrl);
  55245. this._worker.onmessage = this._onMessageFromWorker;
  55246. var message = {
  55247. payload: {},
  55248. taskType: WorkerTaskType.INIT
  55249. };
  55250. this._worker.postMessage(message);
  55251. };
  55252. CollisionCoordinatorWorker.prototype.destroy = function () {
  55253. this._scene.unregisterAfterRender(this._afterRender);
  55254. this._worker.terminate();
  55255. };
  55256. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55257. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55258. this.onMeshUpdated(mesh);
  55259. };
  55260. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55261. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55262. };
  55263. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55264. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55265. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55266. this.onGeometryUpdated(geometry);
  55267. };
  55268. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55269. this._toRemoveGeometryArray.push(geometry.id);
  55270. };
  55271. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55272. var submeshes = [];
  55273. if (mesh.subMeshes) {
  55274. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55275. var boundingInfo = sm.getBoundingInfo();
  55276. return {
  55277. position: idx,
  55278. verticesStart: sm.verticesStart,
  55279. verticesCount: sm.verticesCount,
  55280. indexStart: sm.indexStart,
  55281. indexCount: sm.indexCount,
  55282. hasMaterial: !!sm.getMaterial(),
  55283. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55284. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55285. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55286. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55287. };
  55288. });
  55289. }
  55290. var geometryId = null;
  55291. if (mesh instanceof BABYLON.Mesh) {
  55292. var geometry = mesh.geometry;
  55293. geometryId = geometry ? geometry.id : null;
  55294. }
  55295. else if (mesh instanceof BABYLON.InstancedMesh) {
  55296. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55297. geometryId = geometry ? geometry.id : null;
  55298. }
  55299. var boundingInfo = mesh.getBoundingInfo();
  55300. return {
  55301. uniqueId: mesh.uniqueId,
  55302. id: mesh.id,
  55303. name: mesh.name,
  55304. geometryId: geometryId,
  55305. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55306. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55307. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55308. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55309. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55310. subMeshes: submeshes,
  55311. checkCollisions: mesh.checkCollisions
  55312. };
  55313. };
  55314. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55315. return {
  55316. id: geometry.id,
  55317. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55318. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55319. indices: new Uint32Array(geometry.getIndices() || []),
  55320. };
  55321. };
  55322. return CollisionCoordinatorWorker;
  55323. }());
  55324. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55325. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55326. function CollisionCoordinatorLegacy() {
  55327. this._scaledPosition = BABYLON.Vector3.Zero();
  55328. this._scaledVelocity = BABYLON.Vector3.Zero();
  55329. this._finalPosition = BABYLON.Vector3.Zero();
  55330. }
  55331. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55332. position.divideToRef(collider._radius, this._scaledPosition);
  55333. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55334. collider.collidedMesh = null;
  55335. collider._retry = 0;
  55336. collider._initialVelocity = this._scaledVelocity;
  55337. collider._initialPosition = this._scaledPosition;
  55338. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55339. this._finalPosition.multiplyInPlace(collider._radius);
  55340. //run the callback
  55341. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55342. };
  55343. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55344. this._scene = scene;
  55345. };
  55346. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55347. //Legacy need no destruction method.
  55348. };
  55349. //No update in legacy mode
  55350. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55351. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55352. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55353. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55354. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55355. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55356. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55357. if (excludedMesh === void 0) { excludedMesh = null; }
  55358. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55359. if (collider._retry >= maximumRetry) {
  55360. finalPosition.copyFrom(position);
  55361. return;
  55362. }
  55363. // Check if this is a mesh else camera or -1
  55364. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55365. collider._initialize(position, velocity, closeDistance);
  55366. // Check all meshes
  55367. for (var index = 0; index < this._scene.meshes.length; index++) {
  55368. var mesh = this._scene.meshes[index];
  55369. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55370. mesh._checkCollision(collider);
  55371. }
  55372. }
  55373. if (!collider.collisionFound) {
  55374. position.addToRef(velocity, finalPosition);
  55375. return;
  55376. }
  55377. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55378. collider._getResponse(position, velocity);
  55379. }
  55380. if (velocity.length() <= closeDistance) {
  55381. finalPosition.copyFrom(position);
  55382. return;
  55383. }
  55384. collider._retry++;
  55385. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55386. };
  55387. return CollisionCoordinatorLegacy;
  55388. }());
  55389. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55390. })(BABYLON || (BABYLON = {}));
  55391. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55392. var BABYLON;
  55393. (function (BABYLON) {
  55394. /**
  55395. * A particle represents one of the element emitted by a particle system.
  55396. * This is mainly define by its coordinates, direction, velocity and age.
  55397. */
  55398. var Particle = /** @class */ (function () {
  55399. /**
  55400. * Creates a new instance Particle
  55401. * @param particleSystem the particle system the particle belongs to
  55402. */
  55403. function Particle(
  55404. /**
  55405. * particleSystem the particle system the particle belongs to.
  55406. */
  55407. particleSystem) {
  55408. this.particleSystem = particleSystem;
  55409. /**
  55410. * The world position of the particle in the scene.
  55411. */
  55412. this.position = BABYLON.Vector3.Zero();
  55413. /**
  55414. * The world direction of the particle in the scene.
  55415. */
  55416. this.direction = BABYLON.Vector3.Zero();
  55417. /**
  55418. * The color of the particle.
  55419. */
  55420. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55421. /**
  55422. * The color change of the particle per step.
  55423. */
  55424. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55425. /**
  55426. * Defines how long will the life of the particle be.
  55427. */
  55428. this.lifeTime = 1.0;
  55429. /**
  55430. * The current age of the particle.
  55431. */
  55432. this.age = 0;
  55433. /**
  55434. * The current size of the particle.
  55435. */
  55436. this.size = 0;
  55437. /**
  55438. * The current angle of the particle.
  55439. */
  55440. this.angle = 0;
  55441. /**
  55442. * Defines how fast is the angle changing.
  55443. */
  55444. this.angularSpeed = 0;
  55445. /**
  55446. * Defines the cell index used by the particle to be rendered from a sprite.
  55447. */
  55448. this.cellIndex = 0;
  55449. this._currentFrameCounter = 0;
  55450. if (!this.particleSystem.isAnimationSheetEnabled) {
  55451. return;
  55452. }
  55453. this.updateCellInfoFromSystem();
  55454. }
  55455. Particle.prototype.updateCellInfoFromSystem = function () {
  55456. this.cellIndex = this.particleSystem.startSpriteCellID;
  55457. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55458. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55459. }
  55460. else {
  55461. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55462. }
  55463. };
  55464. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55465. // (ageOffset / scaledUpdateSpeed) / available cells
  55466. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55467. this._currentFrameCounter += scaledUpdateSpeed;
  55468. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55469. this._currentFrameCounter = 0;
  55470. this.cellIndex++;
  55471. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55472. this.cellIndex = this.particleSystem.endSpriteCellID;
  55473. }
  55474. }
  55475. };
  55476. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55477. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55478. this.cellIndex++;
  55479. this._currentFrameCounter = 0;
  55480. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55481. if (this.particleSystem.spriteCellLoop) {
  55482. this.cellIndex = this.particleSystem.startSpriteCellID;
  55483. }
  55484. else {
  55485. this.cellIndex = this.particleSystem.endSpriteCellID;
  55486. }
  55487. }
  55488. }
  55489. else {
  55490. this._currentFrameCounter++;
  55491. }
  55492. };
  55493. /**
  55494. * Copy the properties of particle to another one.
  55495. * @param other the particle to copy the information to.
  55496. */
  55497. Particle.prototype.copyTo = function (other) {
  55498. other.position.copyFrom(this.position);
  55499. other.direction.copyFrom(this.direction);
  55500. other.color.copyFrom(this.color);
  55501. other.colorStep.copyFrom(this.colorStep);
  55502. other.lifeTime = this.lifeTime;
  55503. other.age = this.age;
  55504. other.size = this.size;
  55505. other.angle = this.angle;
  55506. other.angularSpeed = this.angularSpeed;
  55507. other.particleSystem = this.particleSystem;
  55508. other.cellIndex = this.cellIndex;
  55509. };
  55510. return Particle;
  55511. }());
  55512. BABYLON.Particle = Particle;
  55513. })(BABYLON || (BABYLON = {}));
  55514. //# sourceMappingURL=babylon.particle.js.map
  55515. var BABYLON;
  55516. (function (BABYLON) {
  55517. /**
  55518. * This represents a particle system in Babylon.
  55519. * 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.
  55520. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55521. * @example https://doc.babylonjs.com/babylon101/particles
  55522. */
  55523. var ParticleSystem = /** @class */ (function () {
  55524. /**
  55525. * Instantiates a particle system.
  55526. * 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.
  55527. * @param name The name of the particle system
  55528. * @param capacity The max number of particles alive at the same time
  55529. * @param scene The scene the particle system belongs to
  55530. * @param customEffect a custom effect used to change the way particles are rendered by default
  55531. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55532. * @param epsilon Offset used to render the particles
  55533. */
  55534. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55535. if (customEffect === void 0) { customEffect = null; }
  55536. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55537. if (epsilon === void 0) { epsilon = 0.01; }
  55538. var _this = this;
  55539. /**
  55540. * List of animations used by the particle system.
  55541. */
  55542. this.animations = [];
  55543. /**
  55544. * The rendering group used by the Particle system to chose when to render.
  55545. */
  55546. this.renderingGroupId = 0;
  55547. /**
  55548. * The emitter represents the Mesh or position we are attaching the particle system to.
  55549. */
  55550. this.emitter = null;
  55551. /**
  55552. * The maximum number of particles to emit per frame
  55553. */
  55554. this.emitRate = 10;
  55555. /**
  55556. * If you want to launch only a few particles at once, that can be done, as well.
  55557. */
  55558. this.manualEmitCount = -1;
  55559. /**
  55560. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55561. */
  55562. this.updateSpeed = 0.01;
  55563. /**
  55564. * The amount of time the particle system is running (depends of the overall update speed).
  55565. */
  55566. this.targetStopDuration = 0;
  55567. /**
  55568. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55569. */
  55570. this.disposeOnStop = false;
  55571. /**
  55572. * Minimum power of emitting particles.
  55573. */
  55574. this.minEmitPower = 1;
  55575. /**
  55576. * Maximum power of emitting particles.
  55577. */
  55578. this.maxEmitPower = 1;
  55579. /**
  55580. * Minimum life time of emitting particles.
  55581. */
  55582. this.minLifeTime = 1;
  55583. /**
  55584. * Maximum life time of emitting particles.
  55585. */
  55586. this.maxLifeTime = 1;
  55587. /**
  55588. * Minimum Size of emitting particles.
  55589. */
  55590. this.minSize = 1;
  55591. /**
  55592. * Maximum Size of emitting particles.
  55593. */
  55594. this.maxSize = 1;
  55595. /**
  55596. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55597. */
  55598. this.minAngularSpeed = 0;
  55599. /**
  55600. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55601. */
  55602. this.maxAngularSpeed = 0;
  55603. /**
  55604. * The layer mask we are rendering the particles through.
  55605. */
  55606. this.layerMask = 0x0FFFFFFF;
  55607. /**
  55608. * This can help using your own shader to render the particle system.
  55609. * The according effect will be created
  55610. */
  55611. this.customShader = null;
  55612. /**
  55613. * By default particle system starts as soon as they are created. This prevents the
  55614. * automatic start to happen and let you decide when to start emitting particles.
  55615. */
  55616. this.preventAutoStart = false;
  55617. /**
  55618. * Callback triggered when the particle animation is ending.
  55619. */
  55620. this.onAnimationEnd = null;
  55621. /**
  55622. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55623. */
  55624. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55625. /**
  55626. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55627. * to override the particles.
  55628. */
  55629. this.forceDepthWrite = false;
  55630. /**
  55631. * You can use gravity if you want to give an orientation to your particles.
  55632. */
  55633. this.gravity = BABYLON.Vector3.Zero();
  55634. /**
  55635. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55636. */
  55637. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55638. /**
  55639. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55640. */
  55641. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55642. /**
  55643. * Color the particle will have at the end of its lifetime.
  55644. */
  55645. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55646. /**
  55647. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55648. */
  55649. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55650. /**
  55651. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55652. */
  55653. this.spriteCellLoop = true;
  55654. /**
  55655. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55656. */
  55657. this.spriteCellChangeSpeed = 0;
  55658. /**
  55659. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55660. */
  55661. this.startSpriteCellID = 0;
  55662. /**
  55663. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55664. */
  55665. this.endSpriteCellID = 0;
  55666. /**
  55667. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55668. */
  55669. this.spriteCellWidth = 0;
  55670. /**
  55671. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55672. */
  55673. this.spriteCellHeight = 0;
  55674. /**
  55675. * An event triggered when the system is disposed.
  55676. */
  55677. this.onDisposeObservable = new BABYLON.Observable();
  55678. this._particles = new Array();
  55679. this._stockParticles = new Array();
  55680. this._newPartsExcess = 0;
  55681. this._vertexBuffers = {};
  55682. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55683. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55684. this._scaledDirection = BABYLON.Vector3.Zero();
  55685. this._scaledGravity = BABYLON.Vector3.Zero();
  55686. this._currentRenderId = -1;
  55687. this._started = false;
  55688. this._stopped = false;
  55689. this._actualFrame = 0;
  55690. this._vertexBufferSize = 11;
  55691. // start of sub system methods
  55692. /**
  55693. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55694. * Its lifetime will start back at 0.
  55695. */
  55696. this.recycleParticle = function (particle) {
  55697. var lastParticle = _this._particles.pop();
  55698. if (lastParticle !== particle) {
  55699. lastParticle.copyTo(particle);
  55700. }
  55701. _this._stockParticles.push(lastParticle);
  55702. };
  55703. this._createParticle = function () {
  55704. var particle;
  55705. if (_this._stockParticles.length !== 0) {
  55706. particle = _this._stockParticles.pop();
  55707. particle.age = 0;
  55708. particle.cellIndex = _this.startSpriteCellID;
  55709. }
  55710. else {
  55711. particle = new BABYLON.Particle(_this);
  55712. }
  55713. return particle;
  55714. };
  55715. this._emitFromParticle = function (particle) {
  55716. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55717. return;
  55718. }
  55719. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55720. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55721. subSystem._rootParticleSystem = _this;
  55722. _this.activeSubSystems.push(subSystem);
  55723. subSystem.start();
  55724. };
  55725. this._appendParticleVertexes = null;
  55726. this.id = name;
  55727. this.name = name;
  55728. this._capacity = capacity;
  55729. this._epsilon = epsilon;
  55730. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55731. if (isAnimationSheetEnabled) {
  55732. this._vertexBufferSize = 12;
  55733. }
  55734. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55735. this._customEffect = customEffect;
  55736. scene.particleSystems.push(this);
  55737. this._createIndexBuffer();
  55738. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55739. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55740. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55741. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55742. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55743. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55744. if (this._isAnimationSheetEnabled) {
  55745. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55746. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55747. }
  55748. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55749. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55750. this._vertexBuffers["options"] = options;
  55751. // Default emitter type
  55752. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55753. this.updateFunction = function (particles) {
  55754. for (var index = 0; index < particles.length; index++) {
  55755. var particle = particles[index];
  55756. particle.age += _this._scaledUpdateSpeed;
  55757. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55758. _this._emitFromParticle(particle);
  55759. _this.recycleParticle(particle);
  55760. index--;
  55761. continue;
  55762. }
  55763. else {
  55764. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55765. particle.color.addInPlace(_this._scaledColorStep);
  55766. if (particle.color.a < 0)
  55767. particle.color.a = 0;
  55768. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55769. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55770. particle.position.addInPlace(_this._scaledDirection);
  55771. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55772. particle.direction.addInPlace(_this._scaledGravity);
  55773. if (_this._isAnimationSheetEnabled) {
  55774. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55775. }
  55776. }
  55777. }
  55778. };
  55779. }
  55780. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55781. /**
  55782. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55783. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55784. */
  55785. get: function () {
  55786. if (this.particleEmitterType.direction1) {
  55787. return this.particleEmitterType.direction1;
  55788. }
  55789. return BABYLON.Vector3.Zero();
  55790. },
  55791. set: function (value) {
  55792. if (this.particleEmitterType.direction1) {
  55793. this.particleEmitterType.direction1 = value;
  55794. }
  55795. },
  55796. enumerable: true,
  55797. configurable: true
  55798. });
  55799. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55800. /**
  55801. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55802. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55803. */
  55804. get: function () {
  55805. if (this.particleEmitterType.direction2) {
  55806. return this.particleEmitterType.direction2;
  55807. }
  55808. return BABYLON.Vector3.Zero();
  55809. },
  55810. set: function (value) {
  55811. if (this.particleEmitterType.direction2) {
  55812. this.particleEmitterType.direction2 = value;
  55813. }
  55814. },
  55815. enumerable: true,
  55816. configurable: true
  55817. });
  55818. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55819. /**
  55820. * 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.
  55821. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55822. */
  55823. get: function () {
  55824. if (this.particleEmitterType.minEmitBox) {
  55825. return this.particleEmitterType.minEmitBox;
  55826. }
  55827. return BABYLON.Vector3.Zero();
  55828. },
  55829. set: function (value) {
  55830. if (this.particleEmitterType.minEmitBox) {
  55831. this.particleEmitterType.minEmitBox = value;
  55832. }
  55833. },
  55834. enumerable: true,
  55835. configurable: true
  55836. });
  55837. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55838. /**
  55839. * 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.
  55840. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55841. */
  55842. get: function () {
  55843. if (this.particleEmitterType.maxEmitBox) {
  55844. return this.particleEmitterType.maxEmitBox;
  55845. }
  55846. return BABYLON.Vector3.Zero();
  55847. },
  55848. set: function (value) {
  55849. if (this.particleEmitterType.maxEmitBox) {
  55850. this.particleEmitterType.maxEmitBox = value;
  55851. }
  55852. },
  55853. enumerable: true,
  55854. configurable: true
  55855. });
  55856. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55857. /**
  55858. * Sets a callback that will be triggered when the system is disposed.
  55859. */
  55860. set: function (callback) {
  55861. if (this._onDisposeObserver) {
  55862. this.onDisposeObservable.remove(this._onDisposeObserver);
  55863. }
  55864. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55865. },
  55866. enumerable: true,
  55867. configurable: true
  55868. });
  55869. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55870. /**
  55871. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55872. */
  55873. get: function () {
  55874. return this._isAnimationSheetEnabled;
  55875. },
  55876. enumerable: true,
  55877. configurable: true
  55878. });
  55879. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55880. //end of Sub-emitter
  55881. /**
  55882. * Gets the current list of active particles
  55883. */
  55884. get: function () {
  55885. return this._particles;
  55886. },
  55887. enumerable: true,
  55888. configurable: true
  55889. });
  55890. /**
  55891. * Returns the string "ParticleSystem"
  55892. * @returns a string containing the class name
  55893. */
  55894. ParticleSystem.prototype.getClassName = function () {
  55895. return "ParticleSystem";
  55896. };
  55897. ParticleSystem.prototype._createIndexBuffer = function () {
  55898. var indices = [];
  55899. var index = 0;
  55900. for (var count = 0; count < this._capacity; count++) {
  55901. indices.push(index);
  55902. indices.push(index + 1);
  55903. indices.push(index + 2);
  55904. indices.push(index);
  55905. indices.push(index + 2);
  55906. indices.push(index + 3);
  55907. index += 4;
  55908. }
  55909. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55910. };
  55911. /**
  55912. * Gets the maximum number of particles active at the same time.
  55913. * @returns The max number of active particles.
  55914. */
  55915. ParticleSystem.prototype.getCapacity = function () {
  55916. return this._capacity;
  55917. };
  55918. /**
  55919. * Gets Wether there are still active particles in the system.
  55920. * @returns True if it is alive, otherwise false.
  55921. */
  55922. ParticleSystem.prototype.isAlive = function () {
  55923. return this._alive;
  55924. };
  55925. /**
  55926. * Gets Wether the system has been started.
  55927. * @returns True if it has been started, otherwise false.
  55928. */
  55929. ParticleSystem.prototype.isStarted = function () {
  55930. return this._started;
  55931. };
  55932. /**
  55933. * Starts the particle system and begins to emit.
  55934. */
  55935. ParticleSystem.prototype.start = function () {
  55936. this._started = true;
  55937. this._stopped = false;
  55938. this._actualFrame = 0;
  55939. if (this.subEmitters && this.subEmitters.length != 0) {
  55940. this.activeSubSystems = new Array();
  55941. }
  55942. };
  55943. /**
  55944. * Stops the particle system.
  55945. * @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.
  55946. */
  55947. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55948. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55949. this._stopped = true;
  55950. if (stopSubEmitters) {
  55951. this._stopSubEmitters();
  55952. }
  55953. };
  55954. // animation sheet
  55955. /**
  55956. * Remove all active particles
  55957. */
  55958. ParticleSystem.prototype.reset = function () {
  55959. this._stockParticles = [];
  55960. this._particles = [];
  55961. };
  55962. /**
  55963. * @hidden (for internal use only)
  55964. */
  55965. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55966. var offset = index * this._vertexBufferSize;
  55967. this._vertexData[offset] = particle.position.x;
  55968. this._vertexData[offset + 1] = particle.position.y;
  55969. this._vertexData[offset + 2] = particle.position.z;
  55970. this._vertexData[offset + 3] = particle.color.r;
  55971. this._vertexData[offset + 4] = particle.color.g;
  55972. this._vertexData[offset + 5] = particle.color.b;
  55973. this._vertexData[offset + 6] = particle.color.a;
  55974. this._vertexData[offset + 7] = particle.angle;
  55975. this._vertexData[offset + 8] = particle.size;
  55976. this._vertexData[offset + 9] = offsetX;
  55977. this._vertexData[offset + 10] = offsetY;
  55978. };
  55979. /**
  55980. * @hidden (for internal use only)
  55981. */
  55982. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55983. if (offsetX === 0)
  55984. offsetX = this._epsilon;
  55985. else if (offsetX === 1)
  55986. offsetX = 1 - this._epsilon;
  55987. if (offsetY === 0)
  55988. offsetY = this._epsilon;
  55989. else if (offsetY === 1)
  55990. offsetY = 1 - this._epsilon;
  55991. var offset = index * this._vertexBufferSize;
  55992. this._vertexData[offset] = particle.position.x;
  55993. this._vertexData[offset + 1] = particle.position.y;
  55994. this._vertexData[offset + 2] = particle.position.z;
  55995. this._vertexData[offset + 3] = particle.color.r;
  55996. this._vertexData[offset + 4] = particle.color.g;
  55997. this._vertexData[offset + 5] = particle.color.b;
  55998. this._vertexData[offset + 6] = particle.color.a;
  55999. this._vertexData[offset + 7] = particle.angle;
  56000. this._vertexData[offset + 8] = particle.size;
  56001. this._vertexData[offset + 9] = offsetX;
  56002. this._vertexData[offset + 10] = offsetY;
  56003. this._vertexData[offset + 11] = particle.cellIndex;
  56004. };
  56005. ParticleSystem.prototype._stopSubEmitters = function () {
  56006. if (!this.activeSubSystems) {
  56007. return;
  56008. }
  56009. this.activeSubSystems.forEach(function (subSystem) {
  56010. subSystem.stop(true);
  56011. });
  56012. this.activeSubSystems = new Array();
  56013. };
  56014. ParticleSystem.prototype._removeFromRoot = function () {
  56015. if (!this._rootParticleSystem) {
  56016. return;
  56017. }
  56018. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56019. if (index !== -1) {
  56020. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56021. }
  56022. };
  56023. // end of sub system methods
  56024. ParticleSystem.prototype._update = function (newParticles) {
  56025. // Update current
  56026. this._alive = this._particles.length > 0;
  56027. this.updateFunction(this._particles);
  56028. // Add new ones
  56029. var worldMatrix;
  56030. if (this.emitter.position) {
  56031. var emitterMesh = this.emitter;
  56032. worldMatrix = emitterMesh.getWorldMatrix();
  56033. }
  56034. else {
  56035. var emitterPosition = this.emitter;
  56036. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56037. }
  56038. var particle;
  56039. for (var index = 0; index < newParticles; index++) {
  56040. if (this._particles.length === this._capacity) {
  56041. break;
  56042. }
  56043. particle = this._createParticle();
  56044. this._particles.push(particle);
  56045. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56046. if (this.startPositionFunction) {
  56047. this.startPositionFunction(worldMatrix, particle.position, particle);
  56048. }
  56049. else {
  56050. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56051. }
  56052. if (this.startDirectionFunction) {
  56053. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56054. }
  56055. else {
  56056. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56057. }
  56058. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56059. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56060. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56061. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56062. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56063. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56064. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56065. }
  56066. };
  56067. ParticleSystem.prototype._getEffect = function () {
  56068. if (this._customEffect) {
  56069. return this._customEffect;
  56070. }
  56071. ;
  56072. var defines = [];
  56073. if (this._scene.clipPlane) {
  56074. defines.push("#define CLIPPLANE");
  56075. }
  56076. if (this._isAnimationSheetEnabled) {
  56077. defines.push("#define ANIMATESHEET");
  56078. }
  56079. // Effect
  56080. var join = defines.join("\n");
  56081. if (this._cachedDefines !== join) {
  56082. this._cachedDefines = join;
  56083. var attributesNamesOrOptions;
  56084. var effectCreationOption;
  56085. if (this._isAnimationSheetEnabled) {
  56086. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56087. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56088. }
  56089. else {
  56090. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56091. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56092. }
  56093. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56094. }
  56095. return this._effect;
  56096. };
  56097. /**
  56098. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56099. */
  56100. ParticleSystem.prototype.animate = function () {
  56101. if (!this._started)
  56102. return;
  56103. var effect = this._getEffect();
  56104. // Check
  56105. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56106. return;
  56107. if (this._currentRenderId === this._scene.getRenderId()) {
  56108. return;
  56109. }
  56110. this._currentRenderId = this._scene.getRenderId();
  56111. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56112. // determine the number of particles we need to create
  56113. var newParticles;
  56114. if (this.manualEmitCount > -1) {
  56115. newParticles = this.manualEmitCount;
  56116. this._newPartsExcess = 0;
  56117. this.manualEmitCount = 0;
  56118. }
  56119. else {
  56120. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56121. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56122. }
  56123. if (this._newPartsExcess > 1.0) {
  56124. newParticles += this._newPartsExcess >> 0;
  56125. this._newPartsExcess -= this._newPartsExcess >> 0;
  56126. }
  56127. this._alive = false;
  56128. if (!this._stopped) {
  56129. this._actualFrame += this._scaledUpdateSpeed;
  56130. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56131. this.stop();
  56132. }
  56133. else {
  56134. newParticles = 0;
  56135. }
  56136. this._update(newParticles);
  56137. // Stopped?
  56138. if (this._stopped) {
  56139. if (!this._alive) {
  56140. this._started = false;
  56141. if (this.onAnimationEnd) {
  56142. this.onAnimationEnd();
  56143. }
  56144. if (this.disposeOnStop) {
  56145. this._scene._toBeDisposed.push(this);
  56146. }
  56147. }
  56148. }
  56149. // Animation sheet
  56150. if (this._isAnimationSheetEnabled) {
  56151. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56152. }
  56153. else {
  56154. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56155. }
  56156. // Update VBO
  56157. var offset = 0;
  56158. for (var index = 0; index < this._particles.length; index++) {
  56159. var particle = this._particles[index];
  56160. this._appendParticleVertexes(offset, particle);
  56161. offset += 4;
  56162. }
  56163. if (this._vertexBuffer) {
  56164. this._vertexBuffer.update(this._vertexData);
  56165. }
  56166. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56167. this.stop();
  56168. }
  56169. };
  56170. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56171. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56172. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56173. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56174. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56175. };
  56176. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56177. this._appendParticleVertex(offset++, particle, 0, 0);
  56178. this._appendParticleVertex(offset++, particle, 1, 0);
  56179. this._appendParticleVertex(offset++, particle, 1, 1);
  56180. this._appendParticleVertex(offset++, particle, 0, 1);
  56181. };
  56182. /**
  56183. * Rebuilds the particle system.
  56184. */
  56185. ParticleSystem.prototype.rebuild = function () {
  56186. this._createIndexBuffer();
  56187. if (this._vertexBuffer) {
  56188. this._vertexBuffer._rebuild();
  56189. }
  56190. };
  56191. /**
  56192. * Is this system ready to be used/rendered
  56193. * @return true if the system is ready
  56194. */
  56195. ParticleSystem.prototype.isReady = function () {
  56196. var effect = this._getEffect();
  56197. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56198. return false;
  56199. }
  56200. return true;
  56201. };
  56202. /**
  56203. * Renders the particle system in its current state.
  56204. * @returns the current number of particles
  56205. */
  56206. ParticleSystem.prototype.render = function () {
  56207. var effect = this._getEffect();
  56208. // Check
  56209. if (!this.isReady() || !this._particles.length) {
  56210. return 0;
  56211. }
  56212. var engine = this._scene.getEngine();
  56213. // Render
  56214. engine.enableEffect(effect);
  56215. engine.setState(false);
  56216. var viewMatrix = this._scene.getViewMatrix();
  56217. effect.setTexture("diffuseSampler", this.particleTexture);
  56218. effect.setMatrix("view", viewMatrix);
  56219. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56220. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56221. var baseSize = this.particleTexture.getBaseSize();
  56222. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56223. }
  56224. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56225. if (this._scene.clipPlane) {
  56226. var clipPlane = this._scene.clipPlane;
  56227. var invView = viewMatrix.clone();
  56228. invView.invert();
  56229. effect.setMatrix("invView", invView);
  56230. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56231. }
  56232. // VBOs
  56233. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56234. // Draw order
  56235. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56236. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56237. }
  56238. else {
  56239. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56240. }
  56241. if (this.forceDepthWrite) {
  56242. engine.setDepthWrite(true);
  56243. }
  56244. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56245. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56246. return this._particles.length;
  56247. };
  56248. /**
  56249. * Disposes the particle system and free the associated resources
  56250. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56251. */
  56252. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56253. if (disposeTexture === void 0) { disposeTexture = true; }
  56254. if (this._vertexBuffer) {
  56255. this._vertexBuffer.dispose();
  56256. this._vertexBuffer = null;
  56257. }
  56258. if (this._indexBuffer) {
  56259. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56260. this._indexBuffer = null;
  56261. }
  56262. if (disposeTexture && this.particleTexture) {
  56263. this.particleTexture.dispose();
  56264. this.particleTexture = null;
  56265. }
  56266. this._removeFromRoot();
  56267. // Remove from scene
  56268. var index = this._scene.particleSystems.indexOf(this);
  56269. if (index > -1) {
  56270. this._scene.particleSystems.splice(index, 1);
  56271. }
  56272. // Callback
  56273. this.onDisposeObservable.notifyObservers(this);
  56274. this.onDisposeObservable.clear();
  56275. };
  56276. /**
  56277. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56278. * @param radius The radius of the sphere to emit from
  56279. * @returns the emitter
  56280. */
  56281. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56282. if (radius === void 0) { radius = 1; }
  56283. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56284. this.particleEmitterType = particleEmitter;
  56285. return particleEmitter;
  56286. };
  56287. /**
  56288. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56289. * @param radius The radius of the sphere to emit from
  56290. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56291. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56292. * @returns the emitter
  56293. */
  56294. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56295. if (radius === void 0) { radius = 1; }
  56296. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56297. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56298. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56299. this.particleEmitterType = particleEmitter;
  56300. return particleEmitter;
  56301. };
  56302. /**
  56303. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56304. * @param radius The radius of the cone to emit from
  56305. * @param angle The base angle of the cone
  56306. * @returns the emitter
  56307. */
  56308. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56309. if (radius === void 0) { radius = 1; }
  56310. if (angle === void 0) { angle = Math.PI / 4; }
  56311. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56312. this.particleEmitterType = particleEmitter;
  56313. return particleEmitter;
  56314. };
  56315. // 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.
  56316. /**
  56317. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56318. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56319. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56320. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56321. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56322. * @returns the emitter
  56323. */
  56324. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56325. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56326. this.particleEmitterType = particleEmitter;
  56327. this.direction1 = direction1;
  56328. this.direction2 = direction2;
  56329. this.minEmitBox = minEmitBox;
  56330. this.maxEmitBox = maxEmitBox;
  56331. return particleEmitter;
  56332. };
  56333. // Clone
  56334. /**
  56335. * Clones the particle system.
  56336. * @param name The name of the cloned object
  56337. * @param newEmitter The new emitter to use
  56338. * @returns the cloned particle system
  56339. */
  56340. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56341. var custom = null;
  56342. var program = null;
  56343. if (this.customShader != null) {
  56344. program = this.customShader;
  56345. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56346. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56347. }
  56348. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56349. result.customShader = program;
  56350. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56351. if (newEmitter === undefined) {
  56352. newEmitter = this.emitter;
  56353. }
  56354. result.emitter = newEmitter;
  56355. if (this.particleTexture) {
  56356. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56357. }
  56358. if (!this.preventAutoStart) {
  56359. result.start();
  56360. }
  56361. return result;
  56362. };
  56363. /**
  56364. * Serializes the particle system to a JSON object.
  56365. * @returns the JSON object
  56366. */
  56367. ParticleSystem.prototype.serialize = function () {
  56368. var serializationObject = {};
  56369. serializationObject.name = this.name;
  56370. serializationObject.id = this.id;
  56371. // Emitter
  56372. if (this.emitter.position) {
  56373. var emitterMesh = this.emitter;
  56374. serializationObject.emitterId = emitterMesh.id;
  56375. }
  56376. else {
  56377. var emitterPosition = this.emitter;
  56378. serializationObject.emitter = emitterPosition.asArray();
  56379. }
  56380. serializationObject.capacity = this.getCapacity();
  56381. if (this.particleTexture) {
  56382. serializationObject.textureName = this.particleTexture.name;
  56383. }
  56384. // Animations
  56385. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56386. // Particle system
  56387. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56388. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56389. serializationObject.minSize = this.minSize;
  56390. serializationObject.maxSize = this.maxSize;
  56391. serializationObject.minEmitPower = this.minEmitPower;
  56392. serializationObject.maxEmitPower = this.maxEmitPower;
  56393. serializationObject.minLifeTime = this.minLifeTime;
  56394. serializationObject.maxLifeTime = this.maxLifeTime;
  56395. serializationObject.emitRate = this.emitRate;
  56396. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56397. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56398. serializationObject.gravity = this.gravity.asArray();
  56399. serializationObject.direction1 = this.direction1.asArray();
  56400. serializationObject.direction2 = this.direction2.asArray();
  56401. serializationObject.color1 = this.color1.asArray();
  56402. serializationObject.color2 = this.color2.asArray();
  56403. serializationObject.colorDead = this.colorDead.asArray();
  56404. serializationObject.updateSpeed = this.updateSpeed;
  56405. serializationObject.targetStopDuration = this.targetStopDuration;
  56406. serializationObject.textureMask = this.textureMask.asArray();
  56407. serializationObject.blendMode = this.blendMode;
  56408. serializationObject.customShader = this.customShader;
  56409. serializationObject.preventAutoStart = this.preventAutoStart;
  56410. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56411. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56412. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56413. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56414. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56415. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56416. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56417. // Emitter
  56418. if (this.particleEmitterType) {
  56419. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56420. }
  56421. return serializationObject;
  56422. };
  56423. /**
  56424. * Parses a JSON object to create a particle system.
  56425. * @param parsedParticleSystem The JSON object to parse
  56426. * @param scene The scene to create the particle system in
  56427. * @param rootUrl The root url to use to load external dependencies like texture
  56428. * @returns the Parsed particle system
  56429. */
  56430. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56431. var name = parsedParticleSystem.name;
  56432. var custom = null;
  56433. var program = null;
  56434. if (parsedParticleSystem.customShader) {
  56435. program = parsedParticleSystem.customShader;
  56436. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56437. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56438. }
  56439. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56440. particleSystem.customShader = program;
  56441. if (parsedParticleSystem.id) {
  56442. particleSystem.id = parsedParticleSystem.id;
  56443. }
  56444. // Auto start
  56445. if (parsedParticleSystem.preventAutoStart) {
  56446. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56447. }
  56448. // Texture
  56449. if (parsedParticleSystem.textureName) {
  56450. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56451. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56452. }
  56453. // Emitter
  56454. if (parsedParticleSystem.emitterId) {
  56455. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56456. }
  56457. else {
  56458. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56459. }
  56460. // Animations
  56461. if (parsedParticleSystem.animations) {
  56462. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56463. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56464. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56465. }
  56466. }
  56467. if (parsedParticleSystem.autoAnimate) {
  56468. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56469. }
  56470. // Particle system
  56471. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56472. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56473. particleSystem.minSize = parsedParticleSystem.minSize;
  56474. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56475. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56476. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56477. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56478. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56479. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56480. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56481. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56482. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56483. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56484. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56485. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56486. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56487. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56488. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56489. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56490. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56491. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56492. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56493. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56494. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56495. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56496. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56497. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56498. if (!particleSystem.preventAutoStart) {
  56499. particleSystem.start();
  56500. }
  56501. return particleSystem;
  56502. };
  56503. /**
  56504. * Source color is added to the destination color without alpha affecting the result.
  56505. */
  56506. ParticleSystem.BLENDMODE_ONEONE = 0;
  56507. /**
  56508. * Blend current color and particle color using particle’s alpha.
  56509. */
  56510. ParticleSystem.BLENDMODE_STANDARD = 1;
  56511. return ParticleSystem;
  56512. }());
  56513. BABYLON.ParticleSystem = ParticleSystem;
  56514. })(BABYLON || (BABYLON = {}));
  56515. //# sourceMappingURL=babylon.particleSystem.js.map
  56516. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56517. var BABYLON;
  56518. (function (BABYLON) {
  56519. /**
  56520. * Particle emitter emitting particles from the inside of a box.
  56521. * It emits the particles randomly between 2 given directions.
  56522. */
  56523. var BoxParticleEmitter = /** @class */ (function () {
  56524. /**
  56525. * Creates a new instance BoxParticleEmitter
  56526. */
  56527. function BoxParticleEmitter() {
  56528. /**
  56529. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56530. */
  56531. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56532. /**
  56533. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56534. */
  56535. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56536. /**
  56537. * 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.
  56538. */
  56539. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56540. /**
  56541. * 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.
  56542. */
  56543. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56544. }
  56545. /**
  56546. * Called by the particle System when the direction is computed for the created particle.
  56547. * @param emitPower is the power of the particle (speed)
  56548. * @param worldMatrix is the world matrix of the particle system
  56549. * @param directionToUpdate is the direction vector to update with the result
  56550. * @param particle is the particle we are computed the direction for
  56551. */
  56552. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56553. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56554. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56555. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56556. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56557. };
  56558. /**
  56559. * Called by the particle System when the position is computed for the created particle.
  56560. * @param worldMatrix is the world matrix of the particle system
  56561. * @param positionToUpdate is the position vector to update with the result
  56562. * @param particle is the particle we are computed the position for
  56563. */
  56564. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56565. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56566. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56567. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56568. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56569. };
  56570. /**
  56571. * Clones the current emitter and returns a copy of it
  56572. * @returns the new emitter
  56573. */
  56574. BoxParticleEmitter.prototype.clone = function () {
  56575. var newOne = new BoxParticleEmitter();
  56576. BABYLON.Tools.DeepCopy(this, newOne);
  56577. return newOne;
  56578. };
  56579. /**
  56580. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56581. * @param effect defines the update shader
  56582. */
  56583. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56584. effect.setVector3("direction1", this.direction1);
  56585. effect.setVector3("direction2", this.direction2);
  56586. effect.setVector3("minEmitBox", this.minEmitBox);
  56587. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56588. };
  56589. /**
  56590. * Returns a string to use to update the GPU particles update shader
  56591. * @returns a string containng the defines string
  56592. */
  56593. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56594. return "#define BOXEMITTER";
  56595. };
  56596. /**
  56597. * Returns the string "BoxEmitter"
  56598. * @returns a string containing the class name
  56599. */
  56600. BoxParticleEmitter.prototype.getClassName = function () {
  56601. return "BoxEmitter";
  56602. };
  56603. /**
  56604. * Serializes the particle system to a JSON object.
  56605. * @returns the JSON object
  56606. */
  56607. BoxParticleEmitter.prototype.serialize = function () {
  56608. var serializationObject = {};
  56609. serializationObject.type = this.getClassName();
  56610. serializationObject.direction1 = this.direction1.asArray();
  56611. serializationObject.direction2 = this.direction2.asArray();
  56612. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56613. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56614. return serializationObject;
  56615. };
  56616. /**
  56617. * Parse properties from a JSON object
  56618. * @param serializationObject defines the JSON object
  56619. */
  56620. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56621. this.direction1.copyFrom(serializationObject.direction1);
  56622. this.direction2.copyFrom(serializationObject.direction2);
  56623. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56624. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56625. };
  56626. return BoxParticleEmitter;
  56627. }());
  56628. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56629. })(BABYLON || (BABYLON = {}));
  56630. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56631. var BABYLON;
  56632. (function (BABYLON) {
  56633. /**
  56634. * Particle emitter emitting particles from the inside of a cone.
  56635. * It emits the particles alongside the cone volume from the base to the particle.
  56636. * The emission direction might be randomized.
  56637. */
  56638. var ConeParticleEmitter = /** @class */ (function () {
  56639. /**
  56640. * Creates a new instance ConeParticleEmitter
  56641. * @param radius the radius of the emission cone (1 by default)
  56642. * @param angles the cone base angle (PI by default)
  56643. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56644. */
  56645. function ConeParticleEmitter(radius,
  56646. /**
  56647. * The radius of the emission cone.
  56648. */
  56649. angle,
  56650. /**
  56651. * The cone base angle.
  56652. */
  56653. directionRandomizer) {
  56654. if (radius === void 0) { radius = 1; }
  56655. if (angle === void 0) { angle = Math.PI; }
  56656. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56657. this.angle = angle;
  56658. this.directionRandomizer = directionRandomizer;
  56659. this.radius = radius;
  56660. }
  56661. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56662. /**
  56663. * Gets the radius of the emission cone.
  56664. */
  56665. get: function () {
  56666. return this._radius;
  56667. },
  56668. /**
  56669. * Sets the radius of the emission cone.
  56670. */
  56671. set: function (value) {
  56672. this._radius = value;
  56673. if (this.angle !== 0) {
  56674. this._height = value / Math.tan(this.angle / 2);
  56675. }
  56676. else {
  56677. this._height = 1;
  56678. }
  56679. },
  56680. enumerable: true,
  56681. configurable: true
  56682. });
  56683. /**
  56684. * Called by the particle System when the direction is computed for the created particle.
  56685. * @param emitPower is the power of the particle (speed)
  56686. * @param worldMatrix is the world matrix of the particle system
  56687. * @param directionToUpdate is the direction vector to update with the result
  56688. * @param particle is the particle we are computed the direction for
  56689. */
  56690. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56691. if (this.angle === 0) {
  56692. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56693. }
  56694. else {
  56695. // measure the direction Vector from the emitter to the particle.
  56696. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56697. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56698. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56699. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56700. direction.x += randX;
  56701. direction.y += randY;
  56702. direction.z += randZ;
  56703. direction.normalize();
  56704. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56705. }
  56706. };
  56707. /**
  56708. * Called by the particle System when the position is computed for the created particle.
  56709. * @param worldMatrix is the world matrix of the particle system
  56710. * @param positionToUpdate is the position vector to update with the result
  56711. * @param particle is the particle we are computed the position for
  56712. */
  56713. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56714. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56715. var h = BABYLON.Scalar.RandomRange(0, 1);
  56716. // Better distribution in a cone at normal angles.
  56717. h = 1 - h * h;
  56718. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56719. radius = radius * h;
  56720. var randX = radius * Math.sin(s);
  56721. var randZ = radius * Math.cos(s);
  56722. var randY = h * this._height;
  56723. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56724. };
  56725. /**
  56726. * Clones the current emitter and returns a copy of it
  56727. * @returns the new emitter
  56728. */
  56729. ConeParticleEmitter.prototype.clone = function () {
  56730. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56731. BABYLON.Tools.DeepCopy(this, newOne);
  56732. return newOne;
  56733. };
  56734. /**
  56735. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56736. * @param effect defines the update shader
  56737. */
  56738. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56739. effect.setFloat("radius", this.radius);
  56740. effect.setFloat("angle", this.angle);
  56741. effect.setFloat("height", this._height);
  56742. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56743. };
  56744. /**
  56745. * Returns a string to use to update the GPU particles update shader
  56746. * @returns a string containng the defines string
  56747. */
  56748. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56749. return "#define CONEEMITTER";
  56750. };
  56751. /**
  56752. * Returns the string "BoxEmitter"
  56753. * @returns a string containing the class name
  56754. */
  56755. ConeParticleEmitter.prototype.getClassName = function () {
  56756. return "ConeEmitter";
  56757. };
  56758. /**
  56759. * Serializes the particle system to a JSON object.
  56760. * @returns the JSON object
  56761. */
  56762. ConeParticleEmitter.prototype.serialize = function () {
  56763. var serializationObject = {};
  56764. serializationObject.type = this.getClassName();
  56765. serializationObject.radius = this.radius;
  56766. serializationObject.angle = this.angle;
  56767. serializationObject.directionRandomizer = this.directionRandomizer;
  56768. return serializationObject;
  56769. };
  56770. /**
  56771. * Parse properties from a JSON object
  56772. * @param serializationObject defines the JSON object
  56773. */
  56774. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56775. this.radius = serializationObject.radius;
  56776. this.angle = serializationObject.angle;
  56777. this.directionRandomizer = serializationObject.directionRandomizer;
  56778. };
  56779. return ConeParticleEmitter;
  56780. }());
  56781. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56782. })(BABYLON || (BABYLON = {}));
  56783. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56784. var BABYLON;
  56785. (function (BABYLON) {
  56786. /**
  56787. * Particle emitter emitting particles from the inside of a sphere.
  56788. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56789. */
  56790. var SphereParticleEmitter = /** @class */ (function () {
  56791. /**
  56792. * Creates a new instance SphereParticleEmitter
  56793. * @param radius the radius of the emission sphere (1 by default)
  56794. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56795. */
  56796. function SphereParticleEmitter(
  56797. /**
  56798. * The radius of the emission sphere.
  56799. */
  56800. radius,
  56801. /**
  56802. * How much to randomize the particle direction [0-1].
  56803. */
  56804. directionRandomizer) {
  56805. if (radius === void 0) { radius = 1; }
  56806. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56807. this.radius = radius;
  56808. this.directionRandomizer = directionRandomizer;
  56809. }
  56810. /**
  56811. * Called by the particle System when the direction is computed for the created particle.
  56812. * @param emitPower is the power of the particle (speed)
  56813. * @param worldMatrix is the world matrix of the particle system
  56814. * @param directionToUpdate is the direction vector to update with the result
  56815. * @param particle is the particle we are computed the direction for
  56816. */
  56817. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56818. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56819. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56820. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56821. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56822. direction.x += randX;
  56823. direction.y += randY;
  56824. direction.z += randZ;
  56825. direction.normalize();
  56826. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56827. };
  56828. /**
  56829. * Called by the particle System when the position is computed for the created particle.
  56830. * @param worldMatrix is the world matrix of the particle system
  56831. * @param positionToUpdate is the position vector to update with the result
  56832. * @param particle is the particle we are computed the position for
  56833. */
  56834. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56835. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56836. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56837. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56838. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56839. var randY = randRadius * Math.cos(theta);
  56840. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56841. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56842. };
  56843. /**
  56844. * Clones the current emitter and returns a copy of it
  56845. * @returns the new emitter
  56846. */
  56847. SphereParticleEmitter.prototype.clone = function () {
  56848. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56849. BABYLON.Tools.DeepCopy(this, newOne);
  56850. return newOne;
  56851. };
  56852. /**
  56853. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56854. * @param effect defines the update shader
  56855. */
  56856. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56857. effect.setFloat("radius", this.radius);
  56858. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56859. };
  56860. /**
  56861. * Returns a string to use to update the GPU particles update shader
  56862. * @returns a string containng the defines string
  56863. */
  56864. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56865. return "#define SPHEREEMITTER";
  56866. };
  56867. /**
  56868. * Returns the string "SphereParticleEmitter"
  56869. * @returns a string containing the class name
  56870. */
  56871. SphereParticleEmitter.prototype.getClassName = function () {
  56872. return "SphereParticleEmitter";
  56873. };
  56874. /**
  56875. * Serializes the particle system to a JSON object.
  56876. * @returns the JSON object
  56877. */
  56878. SphereParticleEmitter.prototype.serialize = function () {
  56879. var serializationObject = {};
  56880. serializationObject.type = this.getClassName();
  56881. serializationObject.radius = this.radius;
  56882. serializationObject.directionRandomizer = this.directionRandomizer;
  56883. return serializationObject;
  56884. };
  56885. /**
  56886. * Parse properties from a JSON object
  56887. * @param serializationObject defines the JSON object
  56888. */
  56889. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56890. this.radius = serializationObject.radius;
  56891. this.directionRandomizer = serializationObject.directionRandomizer;
  56892. };
  56893. return SphereParticleEmitter;
  56894. }());
  56895. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56896. /**
  56897. * Particle emitter emitting particles from the inside of a sphere.
  56898. * It emits the particles randomly between two vectors.
  56899. */
  56900. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56901. __extends(SphereDirectedParticleEmitter, _super);
  56902. /**
  56903. * Creates a new instance SphereDirectedParticleEmitter
  56904. * @param radius the radius of the emission sphere (1 by default)
  56905. * @param direction1 the min limit of the emission direction (up vector by default)
  56906. * @param direction2 the max limit of the emission direction (up vector by default)
  56907. */
  56908. function SphereDirectedParticleEmitter(radius,
  56909. /**
  56910. * The min limit of the emission direction.
  56911. */
  56912. direction1,
  56913. /**
  56914. * The max limit of the emission direction.
  56915. */
  56916. direction2) {
  56917. if (radius === void 0) { radius = 1; }
  56918. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56919. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56920. var _this = _super.call(this, radius) || this;
  56921. _this.direction1 = direction1;
  56922. _this.direction2 = direction2;
  56923. return _this;
  56924. }
  56925. /**
  56926. * Called by the particle System when the direction is computed for the created particle.
  56927. * @param emitPower is the power of the particle (speed)
  56928. * @param worldMatrix is the world matrix of the particle system
  56929. * @param directionToUpdate is the direction vector to update with the result
  56930. * @param particle is the particle we are computed the direction for
  56931. */
  56932. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56933. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56934. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56935. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56936. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56937. };
  56938. /**
  56939. * Clones the current emitter and returns a copy of it
  56940. * @returns the new emitter
  56941. */
  56942. SphereDirectedParticleEmitter.prototype.clone = function () {
  56943. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56944. BABYLON.Tools.DeepCopy(this, newOne);
  56945. return newOne;
  56946. };
  56947. /**
  56948. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56949. * @param effect defines the update shader
  56950. */
  56951. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56952. effect.setFloat("radius", this.radius);
  56953. effect.setVector3("direction1", this.direction1);
  56954. effect.setVector3("direction2", this.direction2);
  56955. };
  56956. /**
  56957. * Returns a string to use to update the GPU particles update shader
  56958. * @returns a string containng the defines string
  56959. */
  56960. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56961. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56962. };
  56963. /**
  56964. * Returns the string "SphereDirectedParticleEmitter"
  56965. * @returns a string containing the class name
  56966. */
  56967. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56968. return "SphereDirectedParticleEmitter";
  56969. };
  56970. /**
  56971. * Serializes the particle system to a JSON object.
  56972. * @returns the JSON object
  56973. */
  56974. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56975. var serializationObject = _super.prototype.serialize.call(this);
  56976. serializationObject.direction1 = this.direction1.asArray();
  56977. serializationObject.direction2 = this.direction2.asArray();
  56978. return serializationObject;
  56979. };
  56980. /**
  56981. * Parse properties from a JSON object
  56982. * @param serializationObject defines the JSON object
  56983. */
  56984. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56985. _super.prototype.parse.call(this, serializationObject);
  56986. this.direction1.copyFrom(serializationObject.direction1);
  56987. this.direction2.copyFrom(serializationObject.direction2);
  56988. };
  56989. return SphereDirectedParticleEmitter;
  56990. }(SphereParticleEmitter));
  56991. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56992. })(BABYLON || (BABYLON = {}));
  56993. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56994. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56995. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56996. s = arguments[i];
  56997. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56998. t[p] = s[p];
  56999. }
  57000. return t;
  57001. };
  57002. var BABYLON;
  57003. (function (BABYLON) {
  57004. /**
  57005. * This represents a GPU particle system in Babylon
  57006. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57007. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57008. */
  57009. var GPUParticleSystem = /** @class */ (function () {
  57010. /**
  57011. * Instantiates a GPU particle system.
  57012. * 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.
  57013. * @param name The name of the particle system
  57014. * @param capacity The max number of particles alive at the same time
  57015. * @param scene The scene the particle system belongs to
  57016. */
  57017. function GPUParticleSystem(name, options, scene) {
  57018. /**
  57019. * The emitter represents the Mesh or position we are attaching the particle system to.
  57020. */
  57021. this.emitter = null;
  57022. /**
  57023. * The rendering group used by the Particle system to chose when to render.
  57024. */
  57025. this.renderingGroupId = 0;
  57026. /**
  57027. * The layer mask we are rendering the particles through.
  57028. */
  57029. this.layerMask = 0x0FFFFFFF;
  57030. this._targetIndex = 0;
  57031. this._currentRenderId = -1;
  57032. this._started = false;
  57033. this._stopped = false;
  57034. this._timeDelta = 0;
  57035. this._attributesStrideSize = 14;
  57036. this._actualFrame = 0;
  57037. /**
  57038. * List of animations used by the particle system.
  57039. */
  57040. this.animations = [];
  57041. /**
  57042. * An event triggered when the system is disposed.
  57043. */
  57044. this.onDisposeObservable = new BABYLON.Observable();
  57045. /**
  57046. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57047. */
  57048. this.updateSpeed = 0.01;
  57049. /**
  57050. * The amount of time the particle system is running (depends of the overall update speed).
  57051. */
  57052. this.targetStopDuration = 0;
  57053. /**
  57054. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57055. */
  57056. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57057. /**
  57058. * Minimum life time of emitting particles.
  57059. */
  57060. this.minLifeTime = 1;
  57061. /**
  57062. * Maximum life time of emitting particles.
  57063. */
  57064. this.maxLifeTime = 1;
  57065. /**
  57066. * Minimum Size of emitting particles.
  57067. */
  57068. this.minSize = 1;
  57069. /**
  57070. * Maximum Size of emitting particles.
  57071. */
  57072. this.maxSize = 1;
  57073. /**
  57074. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57075. */
  57076. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57077. /**
  57078. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57079. */
  57080. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57081. /**
  57082. * Color the particle will have at the end of its lifetime.
  57083. */
  57084. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57085. /**
  57086. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57087. */
  57088. this.emitRate = 100;
  57089. /**
  57090. * You can use gravity if you want to give an orientation to your particles.
  57091. */
  57092. this.gravity = BABYLON.Vector3.Zero();
  57093. /**
  57094. * Minimum power of emitting particles.
  57095. */
  57096. this.minEmitPower = 1;
  57097. /**
  57098. * Maximum power of emitting particles.
  57099. */
  57100. this.maxEmitPower = 1;
  57101. /**
  57102. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57103. * to override the particles.
  57104. */
  57105. this.forceDepthWrite = false;
  57106. this.id = name;
  57107. this.name = name;
  57108. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57109. this._engine = this._scene.getEngine();
  57110. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57111. this._capacity = fullOptions.capacity;
  57112. this._activeCount = fullOptions.capacity;
  57113. this._currentActiveCount = 0;
  57114. this._scene.particleSystems.push(this);
  57115. this._updateEffectOptions = {
  57116. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57117. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57118. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57119. uniformBuffersNames: [],
  57120. samplers: ["randomSampler"],
  57121. defines: "",
  57122. fallbacks: null,
  57123. onCompiled: null,
  57124. onError: null,
  57125. indexParameters: null,
  57126. maxSimultaneousLights: 0,
  57127. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57128. };
  57129. // Random data
  57130. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57131. var d = [];
  57132. for (var i = 0; i < maxTextureSize; ++i) {
  57133. d.push(Math.random());
  57134. d.push(Math.random());
  57135. d.push(Math.random());
  57136. d.push(Math.random());
  57137. }
  57138. 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);
  57139. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57140. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57141. this._randomTextureSize = maxTextureSize;
  57142. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57143. }
  57144. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57145. /**
  57146. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57147. */
  57148. get: function () {
  57149. if (!BABYLON.Engine.LastCreatedEngine) {
  57150. return false;
  57151. }
  57152. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57153. },
  57154. enumerable: true,
  57155. configurable: true
  57156. });
  57157. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57158. /**
  57159. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57160. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57161. */
  57162. get: function () {
  57163. if (this.particleEmitterType.direction1) {
  57164. return this.particleEmitterType.direction1;
  57165. }
  57166. return BABYLON.Vector3.Zero();
  57167. },
  57168. set: function (value) {
  57169. if (this.particleEmitterType.direction1) {
  57170. this.particleEmitterType.direction1 = value;
  57171. }
  57172. },
  57173. enumerable: true,
  57174. configurable: true
  57175. });
  57176. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57177. /**
  57178. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57179. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57180. */
  57181. get: function () {
  57182. if (this.particleEmitterType.direction2) {
  57183. return this.particleEmitterType.direction2;
  57184. }
  57185. return BABYLON.Vector3.Zero();
  57186. },
  57187. set: function (value) {
  57188. if (this.particleEmitterType.direction2) {
  57189. this.particleEmitterType.direction2 = value;
  57190. }
  57191. },
  57192. enumerable: true,
  57193. configurable: true
  57194. });
  57195. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57196. /**
  57197. * 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.
  57198. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57199. */
  57200. get: function () {
  57201. if (this.particleEmitterType.minEmitBox) {
  57202. return this.particleEmitterType.minEmitBox;
  57203. }
  57204. return BABYLON.Vector3.Zero();
  57205. },
  57206. set: function (value) {
  57207. if (this.particleEmitterType.minEmitBox) {
  57208. this.particleEmitterType.minEmitBox = value;
  57209. }
  57210. },
  57211. enumerable: true,
  57212. configurable: true
  57213. });
  57214. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57215. /**
  57216. * 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.
  57217. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57218. */
  57219. get: function () {
  57220. if (this.particleEmitterType.maxEmitBox) {
  57221. return this.particleEmitterType.maxEmitBox;
  57222. }
  57223. return BABYLON.Vector3.Zero();
  57224. },
  57225. set: function (value) {
  57226. if (this.particleEmitterType.maxEmitBox) {
  57227. this.particleEmitterType.maxEmitBox = value;
  57228. }
  57229. },
  57230. enumerable: true,
  57231. configurable: true
  57232. });
  57233. /**
  57234. * Gets the maximum number of particles active at the same time.
  57235. * @returns The max number of active particles.
  57236. */
  57237. GPUParticleSystem.prototype.getCapacity = function () {
  57238. return this._capacity;
  57239. };
  57240. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57241. /**
  57242. * Gets or set the number of active particles
  57243. */
  57244. get: function () {
  57245. return this._activeCount;
  57246. },
  57247. set: function (value) {
  57248. this._activeCount = Math.min(value, this._capacity);
  57249. },
  57250. enumerable: true,
  57251. configurable: true
  57252. });
  57253. /**
  57254. * Is this system ready to be used/rendered
  57255. * @return true if the system is ready
  57256. */
  57257. GPUParticleSystem.prototype.isReady = function () {
  57258. if (!this._updateEffect) {
  57259. this._recreateUpdateEffect();
  57260. this._recreateRenderEffect();
  57261. return false;
  57262. }
  57263. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57264. return false;
  57265. }
  57266. return true;
  57267. };
  57268. /**
  57269. * Gets Wether the system has been started.
  57270. * @returns True if it has been started, otherwise false.
  57271. */
  57272. GPUParticleSystem.prototype.isStarted = function () {
  57273. return this._started;
  57274. };
  57275. /**
  57276. * Starts the particle system and begins to emit.
  57277. */
  57278. GPUParticleSystem.prototype.start = function () {
  57279. this._started = true;
  57280. this._stopped = false;
  57281. };
  57282. /**
  57283. * Stops the particle system.
  57284. */
  57285. GPUParticleSystem.prototype.stop = function () {
  57286. this._stopped = true;
  57287. };
  57288. /**
  57289. * Remove all active particles
  57290. */
  57291. GPUParticleSystem.prototype.reset = function () {
  57292. this._releaseBuffers();
  57293. this._releaseVAOs();
  57294. this._currentActiveCount = 0;
  57295. this._targetIndex = 0;
  57296. };
  57297. /**
  57298. * Returns the string "GPUParticleSystem"
  57299. * @returns a string containing the class name
  57300. */
  57301. GPUParticleSystem.prototype.getClassName = function () {
  57302. return "GPUParticleSystem";
  57303. };
  57304. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57305. var updateVertexBuffers = {};
  57306. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57307. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57308. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57309. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57310. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57311. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57312. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57313. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57314. this._engine.bindArrayBuffer(null);
  57315. return vao;
  57316. };
  57317. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57318. var renderVertexBuffers = {};
  57319. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57320. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57321. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57322. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57323. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57324. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57325. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57326. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57327. this._engine.bindArrayBuffer(null);
  57328. return vao;
  57329. };
  57330. GPUParticleSystem.prototype._initialize = function (force) {
  57331. if (force === void 0) { force = false; }
  57332. if (this._buffer0 && !force) {
  57333. return;
  57334. }
  57335. var engine = this._scene.getEngine();
  57336. var data = new Array();
  57337. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57338. // position
  57339. data.push(0.0);
  57340. data.push(0.0);
  57341. data.push(0.0);
  57342. // Age and life
  57343. data.push(0.0); // create the particle as a dead one to create a new one at start
  57344. data.push(0.0);
  57345. // Seed
  57346. data.push(Math.random());
  57347. // Size
  57348. data.push(0.0);
  57349. // color
  57350. data.push(0.0);
  57351. data.push(0.0);
  57352. data.push(0.0);
  57353. data.push(0.0);
  57354. // direction
  57355. data.push(0.0);
  57356. data.push(0.0);
  57357. data.push(0.0);
  57358. }
  57359. // Sprite data
  57360. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57361. -0.5, 0.5, 0, 1,
  57362. -0.5, -0.5, 0, 0,
  57363. 0.5, -0.5, 1, 0]);
  57364. // Buffers
  57365. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57366. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57367. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57368. // Update VAO
  57369. this._updateVAO = [];
  57370. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57371. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57372. // Render VAO
  57373. this._renderVAO = [];
  57374. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57375. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57376. // Links
  57377. this._sourceBuffer = this._buffer0;
  57378. this._targetBuffer = this._buffer1;
  57379. };
  57380. /** @hidden */
  57381. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57382. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57383. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57384. return;
  57385. }
  57386. this._updateEffectOptions.defines = defines;
  57387. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57388. };
  57389. /** @hidden */
  57390. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57391. var defines = "";
  57392. if (this._scene.clipPlane) {
  57393. defines = "\n#define CLIPPLANE";
  57394. }
  57395. if (this._renderEffect && this._renderEffect.defines === defines) {
  57396. return;
  57397. }
  57398. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57399. };
  57400. /**
  57401. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57402. */
  57403. GPUParticleSystem.prototype.animate = function () {
  57404. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57405. this._actualFrame += this._timeDelta;
  57406. if (!this._stopped) {
  57407. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57408. this.stop();
  57409. }
  57410. }
  57411. };
  57412. /**
  57413. * Renders the particle system in its current state.
  57414. * @returns the current number of particles
  57415. */
  57416. GPUParticleSystem.prototype.render = function () {
  57417. if (!this._started) {
  57418. return 0;
  57419. }
  57420. this._recreateUpdateEffect();
  57421. this._recreateRenderEffect();
  57422. if (!this.isReady()) {
  57423. return 0;
  57424. }
  57425. if (this._currentRenderId === this._scene.getRenderId()) {
  57426. return 0;
  57427. }
  57428. this._currentRenderId = this._scene.getRenderId();
  57429. // Get everything ready to render
  57430. this._initialize();
  57431. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57432. // Enable update effect
  57433. this._engine.enableEffect(this._updateEffect);
  57434. this._engine.setState(false);
  57435. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57436. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57437. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57438. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57439. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57440. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57441. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57442. this._updateEffect.setDirectColor4("color1", this.color1);
  57443. this._updateEffect.setDirectColor4("color2", this.color2);
  57444. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57445. this._updateEffect.setVector3("gravity", this.gravity);
  57446. if (this.particleEmitterType) {
  57447. this.particleEmitterType.applyToShader(this._updateEffect);
  57448. }
  57449. var emitterWM;
  57450. if (this.emitter.position) {
  57451. var emitterMesh = this.emitter;
  57452. emitterWM = emitterMesh.getWorldMatrix();
  57453. }
  57454. else {
  57455. var emitterPosition = this.emitter;
  57456. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57457. }
  57458. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57459. // Bind source VAO
  57460. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57461. // Update
  57462. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57463. this._engine.setRasterizerState(false);
  57464. this._engine.beginTransformFeedback();
  57465. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57466. this._engine.endTransformFeedback();
  57467. this._engine.setRasterizerState(true);
  57468. this._engine.bindTransformFeedbackBuffer(null);
  57469. // Enable render effect
  57470. this._engine.enableEffect(this._renderEffect);
  57471. var viewMatrix = this._scene.getViewMatrix();
  57472. this._renderEffect.setMatrix("view", viewMatrix);
  57473. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57474. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57475. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57476. if (this._scene.clipPlane) {
  57477. var clipPlane = this._scene.clipPlane;
  57478. var invView = viewMatrix.clone();
  57479. invView.invert();
  57480. this._renderEffect.setMatrix("invView", invView);
  57481. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57482. }
  57483. // Draw order
  57484. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57485. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57486. }
  57487. else {
  57488. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57489. }
  57490. if (this.forceDepthWrite) {
  57491. this._engine.setDepthWrite(true);
  57492. }
  57493. // Bind source VAO
  57494. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57495. // Render
  57496. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57497. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57498. // Switch VAOs
  57499. this._targetIndex++;
  57500. if (this._targetIndex === 2) {
  57501. this._targetIndex = 0;
  57502. }
  57503. // Switch buffers
  57504. var tmpBuffer = this._sourceBuffer;
  57505. this._sourceBuffer = this._targetBuffer;
  57506. this._targetBuffer = tmpBuffer;
  57507. return this._currentActiveCount;
  57508. };
  57509. /**
  57510. * Rebuilds the particle system
  57511. */
  57512. GPUParticleSystem.prototype.rebuild = function () {
  57513. this._initialize(true);
  57514. };
  57515. GPUParticleSystem.prototype._releaseBuffers = function () {
  57516. if (this._buffer0) {
  57517. this._buffer0.dispose();
  57518. this._buffer0 = null;
  57519. }
  57520. if (this._buffer1) {
  57521. this._buffer1.dispose();
  57522. this._buffer1 = null;
  57523. }
  57524. if (this._spriteBuffer) {
  57525. this._spriteBuffer.dispose();
  57526. this._spriteBuffer = null;
  57527. }
  57528. };
  57529. GPUParticleSystem.prototype._releaseVAOs = function () {
  57530. if (!this._updateVAO) {
  57531. return;
  57532. }
  57533. for (var index = 0; index < this._updateVAO.length; index++) {
  57534. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57535. }
  57536. this._updateVAO = [];
  57537. for (var index = 0; index < this._renderVAO.length; index++) {
  57538. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57539. }
  57540. this._renderVAO = [];
  57541. };
  57542. /**
  57543. * Disposes the particle system and free the associated resources
  57544. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57545. */
  57546. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57547. if (disposeTexture === void 0) { disposeTexture = true; }
  57548. var index = this._scene.particleSystems.indexOf(this);
  57549. if (index > -1) {
  57550. this._scene.particleSystems.splice(index, 1);
  57551. }
  57552. this._releaseBuffers();
  57553. this._releaseVAOs();
  57554. if (this._randomTexture) {
  57555. this._randomTexture.dispose();
  57556. this._randomTexture = null;
  57557. }
  57558. if (disposeTexture && this.particleTexture) {
  57559. this.particleTexture.dispose();
  57560. this.particleTexture = null;
  57561. }
  57562. // Callback
  57563. this.onDisposeObservable.notifyObservers(this);
  57564. this.onDisposeObservable.clear();
  57565. };
  57566. /**
  57567. * Clones the particle system.
  57568. * @param name The name of the cloned object
  57569. * @param newEmitter The new emitter to use
  57570. * @returns the cloned particle system
  57571. */
  57572. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57573. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57574. BABYLON.Tools.DeepCopy(this, result);
  57575. if (newEmitter === undefined) {
  57576. newEmitter = this.emitter;
  57577. }
  57578. result.emitter = newEmitter;
  57579. if (this.particleTexture) {
  57580. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57581. }
  57582. return result;
  57583. };
  57584. /**
  57585. * Serializes the particle system to a JSON object.
  57586. * @returns the JSON object
  57587. */
  57588. GPUParticleSystem.prototype.serialize = function () {
  57589. var serializationObject = {};
  57590. serializationObject.name = this.name;
  57591. serializationObject.id = this.id;
  57592. // Emitter
  57593. if (this.emitter.position) {
  57594. var emitterMesh = this.emitter;
  57595. serializationObject.emitterId = emitterMesh.id;
  57596. }
  57597. else {
  57598. var emitterPosition = this.emitter;
  57599. serializationObject.emitter = emitterPosition.asArray();
  57600. }
  57601. serializationObject.capacity = this.getCapacity();
  57602. if (this.particleTexture) {
  57603. serializationObject.textureName = this.particleTexture.name;
  57604. }
  57605. // Animations
  57606. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57607. // Particle system
  57608. serializationObject.activeParticleCount = this.activeParticleCount;
  57609. serializationObject.randomTextureSize = this._randomTextureSize;
  57610. serializationObject.minSize = this.minSize;
  57611. serializationObject.maxSize = this.maxSize;
  57612. serializationObject.minEmitPower = this.minEmitPower;
  57613. serializationObject.maxEmitPower = this.maxEmitPower;
  57614. serializationObject.minLifeTime = this.minLifeTime;
  57615. serializationObject.maxLifeTime = this.maxLifeTime;
  57616. serializationObject.emitRate = this.emitRate;
  57617. serializationObject.gravity = this.gravity.asArray();
  57618. serializationObject.color1 = this.color1.asArray();
  57619. serializationObject.color2 = this.color2.asArray();
  57620. serializationObject.colorDead = this.colorDead.asArray();
  57621. serializationObject.updateSpeed = this.updateSpeed;
  57622. serializationObject.targetStopDuration = this.targetStopDuration;
  57623. serializationObject.blendMode = this.blendMode;
  57624. // Emitter
  57625. if (this.particleEmitterType) {
  57626. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57627. }
  57628. return serializationObject;
  57629. };
  57630. /**
  57631. * Parses a JSON object to create a GPU particle system.
  57632. * @param parsedParticleSystem The JSON object to parse
  57633. * @param scene The scene to create the particle system in
  57634. * @param rootUrl The root url to use to load external dependencies like texture
  57635. * @returns the parsed GPU particle system
  57636. */
  57637. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57638. var name = parsedParticleSystem.name;
  57639. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57640. if (parsedParticleSystem.id) {
  57641. particleSystem.id = parsedParticleSystem.id;
  57642. }
  57643. // Texture
  57644. if (parsedParticleSystem.textureName) {
  57645. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57646. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57647. }
  57648. // Emitter
  57649. if (parsedParticleSystem.emitterId) {
  57650. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57651. }
  57652. else {
  57653. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57654. }
  57655. // Animations
  57656. if (parsedParticleSystem.animations) {
  57657. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57658. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57659. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57660. }
  57661. }
  57662. // Particle system
  57663. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57664. particleSystem.minSize = parsedParticleSystem.minSize;
  57665. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57666. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57667. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57668. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57669. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57670. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57671. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57672. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57673. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57674. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57675. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57676. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57677. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57678. // Emitter
  57679. if (parsedParticleSystem.particleEmitterType) {
  57680. var emitterType = void 0;
  57681. switch (parsedParticleSystem.particleEmitterType.type) {
  57682. case "SphereEmitter":
  57683. emitterType = new BABYLON.SphereParticleEmitter();
  57684. break;
  57685. case "SphereDirectedParticleEmitter":
  57686. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57687. break;
  57688. case "ConeEmitter":
  57689. emitterType = new BABYLON.ConeParticleEmitter();
  57690. break;
  57691. case "BoxEmitter":
  57692. default:
  57693. emitterType = new BABYLON.BoxParticleEmitter();
  57694. break;
  57695. }
  57696. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57697. particleSystem.particleEmitterType = emitterType;
  57698. }
  57699. return particleSystem;
  57700. };
  57701. return GPUParticleSystem;
  57702. }());
  57703. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57704. })(BABYLON || (BABYLON = {}));
  57705. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57706. var BABYLON;
  57707. (function (BABYLON) {
  57708. /**
  57709. * Represents one particle of a solid particle system.
  57710. */
  57711. var SolidParticle = /** @class */ (function () {
  57712. /**
  57713. * Creates a Solid Particle object.
  57714. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57715. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57716. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57717. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57718. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57719. * @param shapeId (integer) is the model shape identifier in the SPS.
  57720. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57721. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57722. */
  57723. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57724. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57725. /**
  57726. * particle global index
  57727. */
  57728. this.idx = 0;
  57729. /**
  57730. * The color of the particle
  57731. */
  57732. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57733. /**
  57734. * The world space position of the particle.
  57735. */
  57736. this.position = BABYLON.Vector3.Zero();
  57737. /**
  57738. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57739. */
  57740. this.rotation = BABYLON.Vector3.Zero();
  57741. /**
  57742. * The scaling of the particle.
  57743. */
  57744. this.scaling = BABYLON.Vector3.One();
  57745. /**
  57746. * The uvs of the particle.
  57747. */
  57748. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57749. /**
  57750. * The current speed of the particle.
  57751. */
  57752. this.velocity = BABYLON.Vector3.Zero();
  57753. /**
  57754. * The pivot point in the particle local space.
  57755. */
  57756. this.pivot = BABYLON.Vector3.Zero();
  57757. /**
  57758. * Must the particle be translated from its pivot point in its local space ?
  57759. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57760. * Default : false
  57761. */
  57762. this.translateFromPivot = false;
  57763. /**
  57764. * Is the particle active or not ?
  57765. */
  57766. this.alive = true;
  57767. /**
  57768. * Is the particle visible or not ?
  57769. */
  57770. this.isVisible = true;
  57771. /**
  57772. * Index of this particle in the global "positions" array (Internal use)
  57773. */
  57774. this._pos = 0;
  57775. /**
  57776. * Index of this particle in the global "indices" array (Internal use)
  57777. */
  57778. this._ind = 0;
  57779. /**
  57780. * ModelShape id of this particle
  57781. */
  57782. this.shapeId = 0;
  57783. /**
  57784. * Index of the particle in its shape id (Internal use)
  57785. */
  57786. this.idxInShape = 0;
  57787. /**
  57788. * Still set as invisible in order to skip useless computations (Internal use)
  57789. */
  57790. this._stillInvisible = false;
  57791. /**
  57792. * Last computed particle rotation matrix
  57793. */
  57794. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57795. /**
  57796. * Parent particle Id, if any.
  57797. * Default null.
  57798. */
  57799. this.parentId = null;
  57800. /**
  57801. * Internal global position in the SPS.
  57802. */
  57803. this._globalPosition = BABYLON.Vector3.Zero();
  57804. this.idx = particleIndex;
  57805. this._pos = positionIndex;
  57806. this._ind = indiceIndex;
  57807. this._model = model;
  57808. this.shapeId = shapeId;
  57809. this.idxInShape = idxInShape;
  57810. this._sps = sps;
  57811. if (modelBoundingInfo) {
  57812. this._modelBoundingInfo = modelBoundingInfo;
  57813. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57814. }
  57815. }
  57816. Object.defineProperty(SolidParticle.prototype, "scale", {
  57817. /**
  57818. * Legacy support, changed scale to scaling
  57819. */
  57820. get: function () {
  57821. return this.scaling;
  57822. },
  57823. /**
  57824. * Legacy support, changed scale to scaling
  57825. */
  57826. set: function (scale) {
  57827. this.scaling = scale;
  57828. },
  57829. enumerable: true,
  57830. configurable: true
  57831. });
  57832. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57833. /**
  57834. * Legacy support, changed quaternion to rotationQuaternion
  57835. */
  57836. get: function () {
  57837. return this.rotationQuaternion;
  57838. },
  57839. /**
  57840. * Legacy support, changed quaternion to rotationQuaternion
  57841. */
  57842. set: function (q) {
  57843. this.rotationQuaternion = q;
  57844. },
  57845. enumerable: true,
  57846. configurable: true
  57847. });
  57848. /**
  57849. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57850. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57851. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57852. * @returns true if it intersects
  57853. */
  57854. SolidParticle.prototype.intersectsMesh = function (target) {
  57855. if (!this._boundingInfo || !target._boundingInfo) {
  57856. return false;
  57857. }
  57858. if (this._sps._bSphereOnly) {
  57859. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57860. }
  57861. return this._boundingInfo.intersects(target._boundingInfo, false);
  57862. };
  57863. return SolidParticle;
  57864. }());
  57865. BABYLON.SolidParticle = SolidParticle;
  57866. /**
  57867. * Represents the shape of the model used by one particle of a solid particle system.
  57868. * SPS internal tool, don't use it manually.
  57869. */
  57870. var ModelShape = /** @class */ (function () {
  57871. /**
  57872. * 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.
  57873. * SPS internal tool, don't use it manually.
  57874. * @hidden
  57875. */
  57876. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57877. /**
  57878. * length of the shape in the model indices array (internal use)
  57879. */
  57880. this._indicesLength = 0;
  57881. this.shapeID = id;
  57882. this._shape = shape;
  57883. this._indicesLength = indicesLength;
  57884. this._shapeUV = shapeUV;
  57885. this._positionFunction = posFunction;
  57886. this._vertexFunction = vtxFunction;
  57887. }
  57888. return ModelShape;
  57889. }());
  57890. BABYLON.ModelShape = ModelShape;
  57891. /**
  57892. * Represents a Depth Sorted Particle in the solid particle system.
  57893. */
  57894. var DepthSortedParticle = /** @class */ (function () {
  57895. function DepthSortedParticle() {
  57896. /**
  57897. * Index of the particle in the "indices" array
  57898. */
  57899. this.ind = 0;
  57900. /**
  57901. * Length of the particle shape in the "indices" array
  57902. */
  57903. this.indicesLength = 0;
  57904. /**
  57905. * Squared distance from the particle to the camera
  57906. */
  57907. this.sqDistance = 0.0;
  57908. }
  57909. return DepthSortedParticle;
  57910. }());
  57911. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57912. })(BABYLON || (BABYLON = {}));
  57913. //# sourceMappingURL=babylon.solidParticle.js.map
  57914. var BABYLON;
  57915. (function (BABYLON) {
  57916. /**
  57917. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57918. *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.
  57919. * The SPS is also a particle system. It provides some methods to manage the particles.
  57920. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57921. *
  57922. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57923. */
  57924. var SolidParticleSystem = /** @class */ (function () {
  57925. /**
  57926. * Creates a SPS (Solid Particle System) object.
  57927. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57928. * @param scene (Scene) is the scene in which the SPS is added.
  57929. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57930. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57931. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57932. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57933. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57934. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57935. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57936. */
  57937. function SolidParticleSystem(name, scene, options) {
  57938. /**
  57939. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57940. * Example : var p = SPS.particles[i];
  57941. */
  57942. this.particles = new Array();
  57943. /**
  57944. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57945. */
  57946. this.nbParticles = 0;
  57947. /**
  57948. * If the particles must ever face the camera (default false). Useful for planar particles.
  57949. */
  57950. this.billboard = false;
  57951. /**
  57952. * Recompute normals when adding a shape
  57953. */
  57954. this.recomputeNormals = true;
  57955. /**
  57956. * This a counter ofr your own usage. It's not set by any SPS functions.
  57957. */
  57958. this.counter = 0;
  57959. /**
  57960. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57961. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57962. */
  57963. this.vars = {};
  57964. /**
  57965. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57966. */
  57967. this._bSphereOnly = false;
  57968. /**
  57969. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57970. */
  57971. this._bSphereRadiusFactor = 1.0;
  57972. this._positions = new Array();
  57973. this._indices = new Array();
  57974. this._normals = new Array();
  57975. this._colors = new Array();
  57976. this._uvs = new Array();
  57977. this._index = 0; // indices index
  57978. this._updatable = true;
  57979. this._pickable = false;
  57980. this._isVisibilityBoxLocked = false;
  57981. this._alwaysVisible = false;
  57982. this._depthSort = false;
  57983. this._shapeCounter = 0;
  57984. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57985. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57986. this._computeParticleColor = true;
  57987. this._computeParticleTexture = true;
  57988. this._computeParticleRotation = true;
  57989. this._computeParticleVertex = false;
  57990. this._computeBoundingBox = false;
  57991. this._depthSortParticles = true;
  57992. this._cam_axisZ = BABYLON.Vector3.Zero();
  57993. this._cam_axisY = BABYLON.Vector3.Zero();
  57994. this._cam_axisX = BABYLON.Vector3.Zero();
  57995. this._axisZ = BABYLON.Axis.Z;
  57996. this._camDir = BABYLON.Vector3.Zero();
  57997. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57998. this._rotMatrix = new BABYLON.Matrix();
  57999. this._invertMatrix = new BABYLON.Matrix();
  58000. this._rotated = BABYLON.Vector3.Zero();
  58001. this._quaternion = new BABYLON.Quaternion();
  58002. this._vertex = BABYLON.Vector3.Zero();
  58003. this._normal = BABYLON.Vector3.Zero();
  58004. this._yaw = 0.0;
  58005. this._pitch = 0.0;
  58006. this._roll = 0.0;
  58007. this._halfroll = 0.0;
  58008. this._halfpitch = 0.0;
  58009. this._halfyaw = 0.0;
  58010. this._sinRoll = 0.0;
  58011. this._cosRoll = 0.0;
  58012. this._sinPitch = 0.0;
  58013. this._cosPitch = 0.0;
  58014. this._sinYaw = 0.0;
  58015. this._cosYaw = 0.0;
  58016. this._mustUnrotateFixedNormals = false;
  58017. this._minimum = BABYLON.Vector3.Zero();
  58018. this._maximum = BABYLON.Vector3.Zero();
  58019. this._minBbox = BABYLON.Vector3.Zero();
  58020. this._maxBbox = BABYLON.Vector3.Zero();
  58021. this._particlesIntersect = false;
  58022. this._depthSortFunction = function (p1, p2) {
  58023. return (p2.sqDistance - p1.sqDistance);
  58024. };
  58025. this._needs32Bits = false;
  58026. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58027. this._scaledPivot = BABYLON.Vector3.Zero();
  58028. this._particleHasParent = false;
  58029. this.name = name;
  58030. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58031. this._camera = scene.activeCamera;
  58032. this._pickable = options ? options.isPickable : false;
  58033. this._depthSort = options ? options.enableDepthSort : false;
  58034. this._particlesIntersect = options ? options.particleIntersection : false;
  58035. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58036. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58037. if (options && options.updatable) {
  58038. this._updatable = options.updatable;
  58039. }
  58040. else {
  58041. this._updatable = true;
  58042. }
  58043. if (this._pickable) {
  58044. this.pickedParticles = [];
  58045. }
  58046. if (this._depthSort) {
  58047. this.depthSortedParticles = [];
  58048. }
  58049. }
  58050. /**
  58051. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58052. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58053. * @returns the created mesh
  58054. */
  58055. SolidParticleSystem.prototype.buildMesh = function () {
  58056. if (this.nbParticles === 0) {
  58057. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58058. this.addShape(triangle, 1);
  58059. triangle.dispose();
  58060. }
  58061. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58062. this._positions32 = new Float32Array(this._positions);
  58063. this._uvs32 = new Float32Array(this._uvs);
  58064. this._colors32 = new Float32Array(this._colors);
  58065. if (this.recomputeNormals) {
  58066. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58067. }
  58068. this._normals32 = new Float32Array(this._normals);
  58069. this._fixedNormal32 = new Float32Array(this._normals);
  58070. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58071. this._unrotateFixedNormals();
  58072. }
  58073. var vertexData = new BABYLON.VertexData();
  58074. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58075. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58076. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58077. if (this._uvs32.length > 0) {
  58078. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58079. }
  58080. if (this._colors32.length > 0) {
  58081. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58082. }
  58083. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58084. vertexData.applyToMesh(mesh, this._updatable);
  58085. this.mesh = mesh;
  58086. this.mesh.isPickable = this._pickable;
  58087. // free memory
  58088. if (!this._depthSort) {
  58089. this._indices = null;
  58090. }
  58091. this._positions = null;
  58092. this._normals = null;
  58093. this._uvs = null;
  58094. this._colors = null;
  58095. if (!this._updatable) {
  58096. this.particles.length = 0;
  58097. }
  58098. return mesh;
  58099. };
  58100. /**
  58101. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58102. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58103. * Thus the particles generated from `digest()` have their property `position` set yet.
  58104. * @param mesh ( Mesh ) is the mesh to be digested
  58105. * @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
  58106. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58107. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58108. * @returns the current SPS
  58109. */
  58110. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58111. var size = (options && options.facetNb) || 1;
  58112. var number = (options && options.number) || 0;
  58113. var delta = (options && options.delta) || 0;
  58114. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58115. var meshInd = mesh.getIndices();
  58116. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58117. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58118. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58119. var f = 0; // facet counter
  58120. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58121. // compute size from number
  58122. if (number) {
  58123. number = (number > totalFacets) ? totalFacets : number;
  58124. size = Math.round(totalFacets / number);
  58125. delta = 0;
  58126. }
  58127. else {
  58128. size = (size > totalFacets) ? totalFacets : size;
  58129. }
  58130. var facetPos = []; // submesh positions
  58131. var facetInd = []; // submesh indices
  58132. var facetUV = []; // submesh UV
  58133. var facetCol = []; // submesh colors
  58134. var barycenter = BABYLON.Vector3.Zero();
  58135. var sizeO = size;
  58136. while (f < totalFacets) {
  58137. size = sizeO + Math.floor((1 + delta) * Math.random());
  58138. if (f > totalFacets - size) {
  58139. size = totalFacets - f;
  58140. }
  58141. // reset temp arrays
  58142. facetPos.length = 0;
  58143. facetInd.length = 0;
  58144. facetUV.length = 0;
  58145. facetCol.length = 0;
  58146. // iterate over "size" facets
  58147. var fi = 0;
  58148. for (var j = f * 3; j < (f + size) * 3; j++) {
  58149. facetInd.push(fi);
  58150. var i = meshInd[j];
  58151. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58152. if (meshUV) {
  58153. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58154. }
  58155. if (meshCol) {
  58156. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58157. }
  58158. fi++;
  58159. }
  58160. // create a model shape for each single particle
  58161. var idx = this.nbParticles;
  58162. var shape = this._posToShape(facetPos);
  58163. var shapeUV = this._uvsToShapeUV(facetUV);
  58164. // compute the barycenter of the shape
  58165. var v;
  58166. for (v = 0; v < shape.length; v++) {
  58167. barycenter.addInPlace(shape[v]);
  58168. }
  58169. barycenter.scaleInPlace(1 / shape.length);
  58170. // shift the shape from its barycenter to the origin
  58171. for (v = 0; v < shape.length; v++) {
  58172. shape[v].subtractInPlace(barycenter);
  58173. }
  58174. var bInfo;
  58175. if (this._particlesIntersect) {
  58176. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58177. }
  58178. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58179. // add the particle in the SPS
  58180. var currentPos = this._positions.length;
  58181. var currentInd = this._indices.length;
  58182. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58183. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58184. // initialize the particle position
  58185. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58186. this._index += shape.length;
  58187. idx++;
  58188. this.nbParticles++;
  58189. this._shapeCounter++;
  58190. f += size;
  58191. }
  58192. return this;
  58193. };
  58194. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58195. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58196. var index = 0;
  58197. var idx = 0;
  58198. for (var p = 0; p < this.particles.length; p++) {
  58199. this._particle = this.particles[p];
  58200. this._shape = this._particle._model._shape;
  58201. if (this._particle.rotationQuaternion) {
  58202. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58203. }
  58204. else {
  58205. this._yaw = this._particle.rotation.y;
  58206. this._pitch = this._particle.rotation.x;
  58207. this._roll = this._particle.rotation.z;
  58208. this._quaternionRotationYPR();
  58209. }
  58210. this._quaternionToRotationMatrix();
  58211. this._rotMatrix.invertToRef(this._invertMatrix);
  58212. for (var pt = 0; pt < this._shape.length; pt++) {
  58213. idx = index + pt * 3;
  58214. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58215. this._fixedNormal32[idx] = this._normal.x;
  58216. this._fixedNormal32[idx + 1] = this._normal.y;
  58217. this._fixedNormal32[idx + 2] = this._normal.z;
  58218. }
  58219. index = idx + 3;
  58220. }
  58221. };
  58222. //reset copy
  58223. SolidParticleSystem.prototype._resetCopy = function () {
  58224. this._copy.position.x = 0;
  58225. this._copy.position.y = 0;
  58226. this._copy.position.z = 0;
  58227. this._copy.rotation.x = 0;
  58228. this._copy.rotation.y = 0;
  58229. this._copy.rotation.z = 0;
  58230. this._copy.rotationQuaternion = null;
  58231. this._copy.scaling.x = 1.0;
  58232. this._copy.scaling.y = 1.0;
  58233. this._copy.scaling.z = 1.0;
  58234. this._copy.uvs.x = 0;
  58235. this._copy.uvs.y = 0;
  58236. this._copy.uvs.z = 1.0;
  58237. this._copy.uvs.w = 1.0;
  58238. this._copy.color = null;
  58239. this._copy.translateFromPivot = false;
  58240. };
  58241. // _meshBuilder : inserts the shape model in the global SPS mesh
  58242. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58243. var i;
  58244. var u = 0;
  58245. var c = 0;
  58246. var n = 0;
  58247. this._resetCopy();
  58248. if (options && options.positionFunction) { // call to custom positionFunction
  58249. options.positionFunction(this._copy, idx, idxInShape);
  58250. this._mustUnrotateFixedNormals = true;
  58251. }
  58252. if (this._copy.rotationQuaternion) {
  58253. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58254. }
  58255. else {
  58256. this._yaw = this._copy.rotation.y;
  58257. this._pitch = this._copy.rotation.x;
  58258. this._roll = this._copy.rotation.z;
  58259. this._quaternionRotationYPR();
  58260. }
  58261. this._quaternionToRotationMatrix();
  58262. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58263. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58264. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58265. if (this._copy.translateFromPivot) {
  58266. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58267. }
  58268. else {
  58269. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58270. }
  58271. for (i = 0; i < shape.length; i++) {
  58272. this._vertex.x = shape[i].x;
  58273. this._vertex.y = shape[i].y;
  58274. this._vertex.z = shape[i].z;
  58275. if (options && options.vertexFunction) {
  58276. options.vertexFunction(this._copy, this._vertex, i);
  58277. }
  58278. this._vertex.x *= this._copy.scaling.x;
  58279. this._vertex.y *= this._copy.scaling.y;
  58280. this._vertex.z *= this._copy.scaling.z;
  58281. this._vertex.x -= this._scaledPivot.x;
  58282. this._vertex.y -= this._scaledPivot.y;
  58283. this._vertex.z -= this._scaledPivot.z;
  58284. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58285. this._rotated.addInPlace(this._pivotBackTranslation);
  58286. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58287. if (meshUV) {
  58288. 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);
  58289. u += 2;
  58290. }
  58291. if (this._copy.color) {
  58292. this._color = this._copy.color;
  58293. }
  58294. else if (meshCol && meshCol[c] !== undefined) {
  58295. this._color.r = meshCol[c];
  58296. this._color.g = meshCol[c + 1];
  58297. this._color.b = meshCol[c + 2];
  58298. this._color.a = meshCol[c + 3];
  58299. }
  58300. else {
  58301. this._color.r = 1.0;
  58302. this._color.g = 1.0;
  58303. this._color.b = 1.0;
  58304. this._color.a = 1.0;
  58305. }
  58306. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58307. c += 4;
  58308. if (!this.recomputeNormals && meshNor) {
  58309. this._normal.x = meshNor[n];
  58310. this._normal.y = meshNor[n + 1];
  58311. this._normal.z = meshNor[n + 2];
  58312. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58313. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58314. n += 3;
  58315. }
  58316. }
  58317. for (i = 0; i < meshInd.length; i++) {
  58318. var current_ind = p + meshInd[i];
  58319. indices.push(current_ind);
  58320. if (current_ind > 65535) {
  58321. this._needs32Bits = true;
  58322. }
  58323. }
  58324. if (this._pickable) {
  58325. var nbfaces = meshInd.length / 3;
  58326. for (i = 0; i < nbfaces; i++) {
  58327. this.pickedParticles.push({ idx: idx, faceId: i });
  58328. }
  58329. }
  58330. if (this._depthSort) {
  58331. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58332. }
  58333. return this._copy;
  58334. };
  58335. // returns a shape array from positions array
  58336. SolidParticleSystem.prototype._posToShape = function (positions) {
  58337. var shape = [];
  58338. for (var i = 0; i < positions.length; i += 3) {
  58339. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58340. }
  58341. return shape;
  58342. };
  58343. // returns a shapeUV array from a Vector4 uvs
  58344. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58345. var shapeUV = [];
  58346. if (uvs) {
  58347. for (var i = 0; i < uvs.length; i++)
  58348. shapeUV.push(uvs[i]);
  58349. }
  58350. return shapeUV;
  58351. };
  58352. // adds a new particle object in the particles array
  58353. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58354. if (bInfo === void 0) { bInfo = null; }
  58355. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58356. this.particles.push(sp);
  58357. return sp;
  58358. };
  58359. /**
  58360. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58361. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58362. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58363. * @param nb (positive integer) the number of particles to be created from this model
  58364. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58365. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58366. * @returns the number of shapes in the system
  58367. */
  58368. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58369. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58370. var meshInd = mesh.getIndices();
  58371. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58372. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58373. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58374. var bbInfo;
  58375. if (this._particlesIntersect) {
  58376. bbInfo = mesh.getBoundingInfo();
  58377. }
  58378. var shape = this._posToShape(meshPos);
  58379. var shapeUV = this._uvsToShapeUV(meshUV);
  58380. var posfunc = options ? options.positionFunction : null;
  58381. var vtxfunc = options ? options.vertexFunction : null;
  58382. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58383. // particles
  58384. var sp;
  58385. var currentCopy;
  58386. var idx = this.nbParticles;
  58387. for (var i = 0; i < nb; i++) {
  58388. var currentPos = this._positions.length;
  58389. var currentInd = this._indices.length;
  58390. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58391. if (this._updatable) {
  58392. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58393. sp.position.copyFrom(currentCopy.position);
  58394. sp.rotation.copyFrom(currentCopy.rotation);
  58395. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58396. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58397. }
  58398. if (currentCopy.color && sp.color) {
  58399. sp.color.copyFrom(currentCopy.color);
  58400. }
  58401. sp.scaling.copyFrom(currentCopy.scaling);
  58402. sp.uvs.copyFrom(currentCopy.uvs);
  58403. }
  58404. this._index += shape.length;
  58405. idx++;
  58406. }
  58407. this.nbParticles += nb;
  58408. this._shapeCounter++;
  58409. return this._shapeCounter - 1;
  58410. };
  58411. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58412. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58413. this._resetCopy();
  58414. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58415. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58416. }
  58417. if (this._copy.rotationQuaternion) {
  58418. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58419. }
  58420. else {
  58421. this._yaw = this._copy.rotation.y;
  58422. this._pitch = this._copy.rotation.x;
  58423. this._roll = this._copy.rotation.z;
  58424. this._quaternionRotationYPR();
  58425. }
  58426. this._quaternionToRotationMatrix();
  58427. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58428. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58429. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58430. if (this._copy.translateFromPivot) {
  58431. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58432. }
  58433. else {
  58434. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58435. }
  58436. this._shape = particle._model._shape;
  58437. for (var pt = 0; pt < this._shape.length; pt++) {
  58438. this._vertex.x = this._shape[pt].x;
  58439. this._vertex.y = this._shape[pt].y;
  58440. this._vertex.z = this._shape[pt].z;
  58441. if (particle._model._vertexFunction) {
  58442. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58443. }
  58444. this._vertex.x *= this._copy.scaling.x;
  58445. this._vertex.y *= this._copy.scaling.y;
  58446. this._vertex.z *= this._copy.scaling.z;
  58447. this._vertex.x -= this._scaledPivot.x;
  58448. this._vertex.y -= this._scaledPivot.y;
  58449. this._vertex.z -= this._scaledPivot.z;
  58450. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58451. this._rotated.addInPlace(this._pivotBackTranslation);
  58452. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58453. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58454. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58455. }
  58456. particle.position.x = 0.0;
  58457. particle.position.y = 0.0;
  58458. particle.position.z = 0.0;
  58459. particle.rotation.x = 0.0;
  58460. particle.rotation.y = 0.0;
  58461. particle.rotation.z = 0.0;
  58462. particle.rotationQuaternion = null;
  58463. particle.scaling.x = 1.0;
  58464. particle.scaling.y = 1.0;
  58465. particle.scaling.z = 1.0;
  58466. particle.uvs.x = 0.0;
  58467. particle.uvs.y = 0.0;
  58468. particle.uvs.z = 1.0;
  58469. particle.uvs.w = 1.0;
  58470. particle.pivot.x = 0.0;
  58471. particle.pivot.y = 0.0;
  58472. particle.pivot.z = 0.0;
  58473. particle.translateFromPivot = false;
  58474. particle.parentId = null;
  58475. };
  58476. /**
  58477. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58478. * @returns the SPS.
  58479. */
  58480. SolidParticleSystem.prototype.rebuildMesh = function () {
  58481. for (var p = 0; p < this.particles.length; p++) {
  58482. this._rebuildParticle(this.particles[p]);
  58483. }
  58484. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58485. return this;
  58486. };
  58487. /**
  58488. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58489. * This method calls `updateParticle()` for each particle of the SPS.
  58490. * For an animated SPS, it is usually called within the render loop.
  58491. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58492. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58493. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58494. * @returns the SPS.
  58495. */
  58496. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58497. if (start === void 0) { start = 0; }
  58498. if (end === void 0) { end = this.nbParticles - 1; }
  58499. if (update === void 0) { update = true; }
  58500. if (!this._updatable) {
  58501. return this;
  58502. }
  58503. // custom beforeUpdate
  58504. this.beforeUpdateParticles(start, end, update);
  58505. this._cam_axisX.x = 1.0;
  58506. this._cam_axisX.y = 0.0;
  58507. this._cam_axisX.z = 0.0;
  58508. this._cam_axisY.x = 0.0;
  58509. this._cam_axisY.y = 1.0;
  58510. this._cam_axisY.z = 0.0;
  58511. this._cam_axisZ.x = 0.0;
  58512. this._cam_axisZ.y = 0.0;
  58513. this._cam_axisZ.z = 1.0;
  58514. // cases when the World Matrix is to be computed first
  58515. if (this.billboard || this._depthSort) {
  58516. this.mesh.computeWorldMatrix(true);
  58517. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58518. }
  58519. // if the particles will always face the camera
  58520. if (this.billboard) {
  58521. // compute the camera position and un-rotate it by the current mesh rotation
  58522. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58523. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58524. this._cam_axisZ.normalize();
  58525. // same for camera up vector extracted from the cam view matrix
  58526. var view = this._camera.getViewMatrix(true);
  58527. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58528. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58529. this._cam_axisY.normalize();
  58530. this._cam_axisX.normalize();
  58531. }
  58532. // if depthSort, compute the camera global position in the mesh local system
  58533. if (this._depthSort) {
  58534. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58535. }
  58536. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58537. var idx = 0; // current position index in the global array positions32
  58538. var index = 0; // position start index in the global array positions32 of the current particle
  58539. var colidx = 0; // current color index in the global array colors32
  58540. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58541. var uvidx = 0; // current uv index in the global array uvs32
  58542. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58543. var pt = 0; // current index in the particle model shape
  58544. if (this.mesh.isFacetDataEnabled) {
  58545. this._computeBoundingBox = true;
  58546. }
  58547. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58548. if (this._computeBoundingBox) {
  58549. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58550. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58551. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58552. }
  58553. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58554. if (this.mesh._boundingInfo) {
  58555. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58556. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58557. }
  58558. }
  58559. }
  58560. // particle loop
  58561. index = this.particles[start]._pos;
  58562. var vpos = (index / 3) | 0;
  58563. colorIndex = vpos * 4;
  58564. uvIndex = vpos * 2;
  58565. for (var p = start; p <= end; p++) {
  58566. this._particle = this.particles[p];
  58567. this._shape = this._particle._model._shape;
  58568. this._shapeUV = this._particle._model._shapeUV;
  58569. // call to custom user function to update the particle properties
  58570. this.updateParticle(this._particle);
  58571. // camera-particle distance for depth sorting
  58572. if (this._depthSort && this._depthSortParticles) {
  58573. var dsp = this.depthSortedParticles[p];
  58574. dsp.ind = this._particle._ind;
  58575. dsp.indicesLength = this._particle._model._indicesLength;
  58576. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58577. }
  58578. // skip the computations for inactive or already invisible particles
  58579. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58580. // increment indexes for the next particle
  58581. pt = this._shape.length;
  58582. index += pt * 3;
  58583. colorIndex += pt * 4;
  58584. uvIndex += pt * 2;
  58585. continue;
  58586. }
  58587. if (this._particle.isVisible) {
  58588. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58589. this._particleHasParent = (this._particle.parentId !== null);
  58590. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58591. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58592. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58593. // particle rotation matrix
  58594. if (this.billboard) {
  58595. this._particle.rotation.x = 0.0;
  58596. this._particle.rotation.y = 0.0;
  58597. }
  58598. if (this._computeParticleRotation || this.billboard) {
  58599. if (this._particle.rotationQuaternion) {
  58600. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58601. }
  58602. else {
  58603. this._yaw = this._particle.rotation.y;
  58604. this._pitch = this._particle.rotation.x;
  58605. this._roll = this._particle.rotation.z;
  58606. this._quaternionRotationYPR();
  58607. }
  58608. this._quaternionToRotationMatrix();
  58609. }
  58610. if (this._particleHasParent) {
  58611. this._parent = this.particles[this._particle.parentId];
  58612. 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];
  58613. 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];
  58614. 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];
  58615. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58616. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58617. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58618. if (this._computeParticleRotation || this.billboard) {
  58619. 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];
  58620. 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];
  58621. 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];
  58622. 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];
  58623. 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];
  58624. 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];
  58625. 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];
  58626. 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];
  58627. 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];
  58628. }
  58629. }
  58630. else {
  58631. this._particle._globalPosition.x = this._particle.position.x;
  58632. this._particle._globalPosition.y = this._particle.position.y;
  58633. this._particle._globalPosition.z = this._particle.position.z;
  58634. if (this._computeParticleRotation || this.billboard) {
  58635. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58636. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58637. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58638. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58639. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58640. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58641. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58642. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58643. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58644. }
  58645. }
  58646. if (this._particle.translateFromPivot) {
  58647. this._pivotBackTranslation.x = 0.0;
  58648. this._pivotBackTranslation.y = 0.0;
  58649. this._pivotBackTranslation.z = 0.0;
  58650. }
  58651. else {
  58652. this._pivotBackTranslation.x = this._scaledPivot.x;
  58653. this._pivotBackTranslation.y = this._scaledPivot.y;
  58654. this._pivotBackTranslation.z = this._scaledPivot.z;
  58655. }
  58656. // particle vertex loop
  58657. for (pt = 0; pt < this._shape.length; pt++) {
  58658. idx = index + pt * 3;
  58659. colidx = colorIndex + pt * 4;
  58660. uvidx = uvIndex + pt * 2;
  58661. this._vertex.x = this._shape[pt].x;
  58662. this._vertex.y = this._shape[pt].y;
  58663. this._vertex.z = this._shape[pt].z;
  58664. if (this._computeParticleVertex) {
  58665. this.updateParticleVertex(this._particle, this._vertex, pt);
  58666. }
  58667. // positions
  58668. this._vertex.x *= this._particle.scaling.x;
  58669. this._vertex.y *= this._particle.scaling.y;
  58670. this._vertex.z *= this._particle.scaling.z;
  58671. this._vertex.x -= this._scaledPivot.x;
  58672. this._vertex.y -= this._scaledPivot.y;
  58673. this._vertex.z -= this._scaledPivot.z;
  58674. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58675. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58676. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58677. this._rotated.x += this._pivotBackTranslation.x;
  58678. this._rotated.y += this._pivotBackTranslation.y;
  58679. this._rotated.z += this._pivotBackTranslation.z;
  58680. 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;
  58681. 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;
  58682. 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;
  58683. if (this._computeBoundingBox) {
  58684. if (this._positions32[idx] < this._minimum.x) {
  58685. this._minimum.x = this._positions32[idx];
  58686. }
  58687. if (this._positions32[idx] > this._maximum.x) {
  58688. this._maximum.x = this._positions32[idx];
  58689. }
  58690. if (this._positions32[idx + 1] < this._minimum.y) {
  58691. this._minimum.y = this._positions32[idx + 1];
  58692. }
  58693. if (this._positions32[idx + 1] > this._maximum.y) {
  58694. this._maximum.y = this._positions32[idx + 1];
  58695. }
  58696. if (this._positions32[idx + 2] < this._minimum.z) {
  58697. this._minimum.z = this._positions32[idx + 2];
  58698. }
  58699. if (this._positions32[idx + 2] > this._maximum.z) {
  58700. this._maximum.z = this._positions32[idx + 2];
  58701. }
  58702. }
  58703. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58704. if (!this._computeParticleVertex) {
  58705. this._normal.x = this._fixedNormal32[idx];
  58706. this._normal.y = this._fixedNormal32[idx + 1];
  58707. this._normal.z = this._fixedNormal32[idx + 2];
  58708. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58709. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58710. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58711. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58712. 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;
  58713. 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;
  58714. }
  58715. if (this._computeParticleColor && this._particle.color) {
  58716. this._colors32[colidx] = this._particle.color.r;
  58717. this._colors32[colidx + 1] = this._particle.color.g;
  58718. this._colors32[colidx + 2] = this._particle.color.b;
  58719. this._colors32[colidx + 3] = this._particle.color.a;
  58720. }
  58721. if (this._computeParticleTexture) {
  58722. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58723. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58724. }
  58725. }
  58726. }
  58727. // particle just set invisible : scaled to zero and positioned at the origin
  58728. else {
  58729. this._particle._stillInvisible = true; // mark the particle as invisible
  58730. for (pt = 0; pt < this._shape.length; pt++) {
  58731. idx = index + pt * 3;
  58732. colidx = colorIndex + pt * 4;
  58733. uvidx = uvIndex + pt * 2;
  58734. this._positions32[idx] = 0.0;
  58735. this._positions32[idx + 1] = 0.0;
  58736. this._positions32[idx + 2] = 0.0;
  58737. this._normals32[idx] = 0.0;
  58738. this._normals32[idx + 1] = 0.0;
  58739. this._normals32[idx + 2] = 0.0;
  58740. if (this._computeParticleColor && this._particle.color) {
  58741. this._colors32[colidx] = this._particle.color.r;
  58742. this._colors32[colidx + 1] = this._particle.color.g;
  58743. this._colors32[colidx + 2] = this._particle.color.b;
  58744. this._colors32[colidx + 3] = this._particle.color.a;
  58745. }
  58746. if (this._computeParticleTexture) {
  58747. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58748. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58749. }
  58750. }
  58751. }
  58752. // if the particle intersections must be computed : update the bbInfo
  58753. if (this._particlesIntersect) {
  58754. var bInfo = this._particle._boundingInfo;
  58755. var bBox = bInfo.boundingBox;
  58756. var bSphere = bInfo.boundingSphere;
  58757. if (!this._bSphereOnly) {
  58758. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58759. for (var b = 0; b < bBox.vectors.length; b++) {
  58760. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58761. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58762. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58763. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58764. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58765. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58766. 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;
  58767. 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;
  58768. 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;
  58769. }
  58770. bBox._update(this.mesh._worldMatrix);
  58771. }
  58772. // place and scale the particle bouding sphere in the SPS local system, then update it
  58773. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58774. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58775. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58776. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58777. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58778. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58779. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58780. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58781. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58782. 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));
  58783. bSphere._update(this.mesh._worldMatrix);
  58784. }
  58785. // increment indexes for the next particle
  58786. index = idx + 3;
  58787. colorIndex = colidx + 4;
  58788. uvIndex = uvidx + 2;
  58789. }
  58790. // if the VBO must be updated
  58791. if (update) {
  58792. if (this._computeParticleColor) {
  58793. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58794. }
  58795. if (this._computeParticleTexture) {
  58796. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58797. }
  58798. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58799. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58800. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58801. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58802. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58803. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58804. for (var i = 0; i < this._normals32.length; i++) {
  58805. this._fixedNormal32[i] = this._normals32[i];
  58806. }
  58807. }
  58808. if (!this.mesh.areNormalsFrozen) {
  58809. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58810. }
  58811. }
  58812. if (this._depthSort && this._depthSortParticles) {
  58813. this.depthSortedParticles.sort(this._depthSortFunction);
  58814. var dspl = this.depthSortedParticles.length;
  58815. var sorted = 0;
  58816. var lind = 0;
  58817. var sind = 0;
  58818. var sid = 0;
  58819. for (sorted = 0; sorted < dspl; sorted++) {
  58820. lind = this.depthSortedParticles[sorted].indicesLength;
  58821. sind = this.depthSortedParticles[sorted].ind;
  58822. for (var i = 0; i < lind; i++) {
  58823. this._indices32[sid] = this._indices[sind + i];
  58824. sid++;
  58825. }
  58826. }
  58827. this.mesh.updateIndices(this._indices32);
  58828. }
  58829. }
  58830. if (this._computeBoundingBox) {
  58831. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58832. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58833. }
  58834. this.afterUpdateParticles(start, end, update);
  58835. return this;
  58836. };
  58837. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58838. this._halfroll = this._roll * 0.5;
  58839. this._halfpitch = this._pitch * 0.5;
  58840. this._halfyaw = this._yaw * 0.5;
  58841. this._sinRoll = Math.sin(this._halfroll);
  58842. this._cosRoll = Math.cos(this._halfroll);
  58843. this._sinPitch = Math.sin(this._halfpitch);
  58844. this._cosPitch = Math.cos(this._halfpitch);
  58845. this._sinYaw = Math.sin(this._halfyaw);
  58846. this._cosYaw = Math.cos(this._halfyaw);
  58847. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58848. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58849. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58850. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58851. };
  58852. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58853. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58854. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58855. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58856. this._rotMatrix.m[3] = 0;
  58857. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58858. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58859. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58860. this._rotMatrix.m[7] = 0;
  58861. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58862. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58863. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58864. this._rotMatrix.m[11] = 0;
  58865. this._rotMatrix.m[12] = 0;
  58866. this._rotMatrix.m[13] = 0;
  58867. this._rotMatrix.m[14] = 0;
  58868. this._rotMatrix.m[15] = 1.0;
  58869. };
  58870. /**
  58871. * Disposes the SPS.
  58872. */
  58873. SolidParticleSystem.prototype.dispose = function () {
  58874. this.mesh.dispose();
  58875. this.vars = null;
  58876. // drop references to internal big arrays for the GC
  58877. this._positions = null;
  58878. this._indices = null;
  58879. this._normals = null;
  58880. this._uvs = null;
  58881. this._colors = null;
  58882. this._indices32 = null;
  58883. this._positions32 = null;
  58884. this._normals32 = null;
  58885. this._fixedNormal32 = null;
  58886. this._uvs32 = null;
  58887. this._colors32 = null;
  58888. this.pickedParticles = null;
  58889. };
  58890. /**
  58891. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58892. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58893. * @returns the SPS.
  58894. */
  58895. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58896. if (!this._isVisibilityBoxLocked) {
  58897. this.mesh.refreshBoundingInfo();
  58898. }
  58899. return this;
  58900. };
  58901. /**
  58902. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58903. * @param size the size (float) of the visibility box
  58904. * note : this doesn't lock the SPS mesh bounding box.
  58905. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58906. */
  58907. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58908. var vis = size / 2;
  58909. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58910. };
  58911. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58912. /**
  58913. * Gets whether the SPS as always visible or not
  58914. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58915. */
  58916. get: function () {
  58917. return this._alwaysVisible;
  58918. },
  58919. /**
  58920. * Sets the SPS as always visible or not
  58921. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58922. */
  58923. set: function (val) {
  58924. this._alwaysVisible = val;
  58925. this.mesh.alwaysSelectAsActiveMesh = val;
  58926. },
  58927. enumerable: true,
  58928. configurable: true
  58929. });
  58930. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58931. /**
  58932. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58933. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58934. */
  58935. get: function () {
  58936. return this._isVisibilityBoxLocked;
  58937. },
  58938. /**
  58939. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58940. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58941. */
  58942. set: function (val) {
  58943. this._isVisibilityBoxLocked = val;
  58944. var boundingInfo = this.mesh.getBoundingInfo();
  58945. boundingInfo.isLocked = val;
  58946. },
  58947. enumerable: true,
  58948. configurable: true
  58949. });
  58950. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58951. /**
  58952. * Gets if `setParticles()` computes the particle rotations or not.
  58953. * Default value : true. The SPS is faster when it's set to false.
  58954. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58955. */
  58956. get: function () {
  58957. return this._computeParticleRotation;
  58958. },
  58959. /**
  58960. * Tells to `setParticles()` to compute the particle rotations or not.
  58961. * Default value : true. The SPS is faster when it's set to false.
  58962. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58963. */
  58964. set: function (val) {
  58965. this._computeParticleRotation = val;
  58966. },
  58967. enumerable: true,
  58968. configurable: true
  58969. });
  58970. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58971. /**
  58972. * Gets if `setParticles()` computes the particle colors or not.
  58973. * Default value : true. The SPS is faster when it's set to false.
  58974. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58975. */
  58976. get: function () {
  58977. return this._computeParticleColor;
  58978. },
  58979. /**
  58980. * Tells to `setParticles()` to compute the particle colors or not.
  58981. * Default value : true. The SPS is faster when it's set to false.
  58982. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58983. */
  58984. set: function (val) {
  58985. this._computeParticleColor = val;
  58986. },
  58987. enumerable: true,
  58988. configurable: true
  58989. });
  58990. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58991. /**
  58992. * Gets if `setParticles()` computes the particle textures or not.
  58993. * Default value : true. The SPS is faster when it's set to false.
  58994. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58995. */
  58996. get: function () {
  58997. return this._computeParticleTexture;
  58998. },
  58999. set: function (val) {
  59000. this._computeParticleTexture = val;
  59001. },
  59002. enumerable: true,
  59003. configurable: true
  59004. });
  59005. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59006. /**
  59007. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59008. * Default value : false. The SPS is faster when it's set to false.
  59009. * Note : the particle custom vertex positions aren't stored values.
  59010. */
  59011. get: function () {
  59012. return this._computeParticleVertex;
  59013. },
  59014. /**
  59015. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59016. * Default value : false. The SPS is faster when it's set to false.
  59017. * Note : the particle custom vertex positions aren't stored values.
  59018. */
  59019. set: function (val) {
  59020. this._computeParticleVertex = val;
  59021. },
  59022. enumerable: true,
  59023. configurable: true
  59024. });
  59025. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59026. /**
  59027. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59028. */
  59029. get: function () {
  59030. return this._computeBoundingBox;
  59031. },
  59032. /**
  59033. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59034. */
  59035. set: function (val) {
  59036. this._computeBoundingBox = val;
  59037. },
  59038. enumerable: true,
  59039. configurable: true
  59040. });
  59041. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59042. /**
  59043. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59044. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59045. * Default : `true`
  59046. */
  59047. get: function () {
  59048. return this._depthSortParticles;
  59049. },
  59050. /**
  59051. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59052. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59053. * Default : `true`
  59054. */
  59055. set: function (val) {
  59056. this._depthSortParticles = val;
  59057. },
  59058. enumerable: true,
  59059. configurable: true
  59060. });
  59061. // =======================================================================
  59062. // Particle behavior logic
  59063. // these following methods may be overwritten by the user to fit his needs
  59064. /**
  59065. * This function does nothing. It may be overwritten to set all the particle first values.
  59066. * The SPS doesn't call this function, you may have to call it by your own.
  59067. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59068. */
  59069. SolidParticleSystem.prototype.initParticles = function () {
  59070. };
  59071. /**
  59072. * This function does nothing. It may be overwritten to recycle a particle.
  59073. * The SPS doesn't call this function, you may have to call it by your own.
  59074. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59075. * @param particle The particle to recycle
  59076. * @returns the recycled particle
  59077. */
  59078. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59079. return particle;
  59080. };
  59081. /**
  59082. * Updates a particle : this function should be overwritten by the user.
  59083. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59084. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59085. * @example : just set a particle position or velocity and recycle conditions
  59086. * @param particle The particle to update
  59087. * @returns the updated particle
  59088. */
  59089. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59090. return particle;
  59091. };
  59092. /**
  59093. * Updates a vertex of a particle : it can be overwritten by the user.
  59094. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59095. * @param particle the current particle
  59096. * @param vertex the current index of the current particle
  59097. * @param pt the index of the current vertex in the particle shape
  59098. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59099. * @example : just set a vertex particle position
  59100. * @returns the updated vertex
  59101. */
  59102. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59103. return vertex;
  59104. };
  59105. /**
  59106. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59107. * This does nothing and may be overwritten by the user.
  59108. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59109. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59110. * @param update the boolean update value actually passed to setParticles()
  59111. */
  59112. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59113. };
  59114. /**
  59115. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59116. * This will be passed three parameters.
  59117. * This does nothing and may be overwritten by the user.
  59118. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59119. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59120. * @param update the boolean update value actually passed to setParticles()
  59121. */
  59122. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59123. };
  59124. return SolidParticleSystem;
  59125. }());
  59126. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59127. })(BABYLON || (BABYLON = {}));
  59128. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59129. var BABYLON;
  59130. (function (BABYLON) {
  59131. var ShaderMaterial = /** @class */ (function (_super) {
  59132. __extends(ShaderMaterial, _super);
  59133. function ShaderMaterial(name, scene, shaderPath, options) {
  59134. var _this = _super.call(this, name, scene) || this;
  59135. _this._textures = {};
  59136. _this._textureArrays = {};
  59137. _this._floats = {};
  59138. _this._ints = {};
  59139. _this._floatsArrays = {};
  59140. _this._colors3 = {};
  59141. _this._colors3Arrays = {};
  59142. _this._colors4 = {};
  59143. _this._vectors2 = {};
  59144. _this._vectors3 = {};
  59145. _this._vectors4 = {};
  59146. _this._matrices = {};
  59147. _this._matrices3x3 = {};
  59148. _this._matrices2x2 = {};
  59149. _this._vectors2Arrays = {};
  59150. _this._vectors3Arrays = {};
  59151. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59152. _this._shaderPath = shaderPath;
  59153. options.needAlphaBlending = options.needAlphaBlending || false;
  59154. options.needAlphaTesting = options.needAlphaTesting || false;
  59155. options.attributes = options.attributes || ["position", "normal", "uv"];
  59156. options.uniforms = options.uniforms || ["worldViewProjection"];
  59157. options.uniformBuffers = options.uniformBuffers || [];
  59158. options.samplers = options.samplers || [];
  59159. options.defines = options.defines || [];
  59160. _this._options = options;
  59161. return _this;
  59162. }
  59163. ShaderMaterial.prototype.getClassName = function () {
  59164. return "ShaderMaterial";
  59165. };
  59166. ShaderMaterial.prototype.needAlphaBlending = function () {
  59167. return this._options.needAlphaBlending;
  59168. };
  59169. ShaderMaterial.prototype.needAlphaTesting = function () {
  59170. return this._options.needAlphaTesting;
  59171. };
  59172. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59173. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59174. this._options.uniforms.push(uniformName);
  59175. }
  59176. };
  59177. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59178. if (this._options.samplers.indexOf(name) === -1) {
  59179. this._options.samplers.push(name);
  59180. }
  59181. this._textures[name] = texture;
  59182. return this;
  59183. };
  59184. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59185. if (this._options.samplers.indexOf(name) === -1) {
  59186. this._options.samplers.push(name);
  59187. }
  59188. this._checkUniform(name);
  59189. this._textureArrays[name] = textures;
  59190. return this;
  59191. };
  59192. ShaderMaterial.prototype.setFloat = function (name, value) {
  59193. this._checkUniform(name);
  59194. this._floats[name] = value;
  59195. return this;
  59196. };
  59197. ShaderMaterial.prototype.setInt = function (name, value) {
  59198. this._checkUniform(name);
  59199. this._ints[name] = value;
  59200. return this;
  59201. };
  59202. ShaderMaterial.prototype.setFloats = function (name, value) {
  59203. this._checkUniform(name);
  59204. this._floatsArrays[name] = value;
  59205. return this;
  59206. };
  59207. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59208. this._checkUniform(name);
  59209. this._colors3[name] = value;
  59210. return this;
  59211. };
  59212. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59213. this._checkUniform(name);
  59214. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59215. color.toArray(arr, arr.length);
  59216. return arr;
  59217. }, []);
  59218. return this;
  59219. };
  59220. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59221. this._checkUniform(name);
  59222. this._colors4[name] = value;
  59223. return this;
  59224. };
  59225. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59226. this._checkUniform(name);
  59227. this._vectors2[name] = value;
  59228. return this;
  59229. };
  59230. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59231. this._checkUniform(name);
  59232. this._vectors3[name] = value;
  59233. return this;
  59234. };
  59235. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59236. this._checkUniform(name);
  59237. this._vectors4[name] = value;
  59238. return this;
  59239. };
  59240. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59241. this._checkUniform(name);
  59242. this._matrices[name] = value;
  59243. return this;
  59244. };
  59245. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59246. this._checkUniform(name);
  59247. this._matrices3x3[name] = value;
  59248. return this;
  59249. };
  59250. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59251. this._checkUniform(name);
  59252. this._matrices2x2[name] = value;
  59253. return this;
  59254. };
  59255. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59256. this._checkUniform(name);
  59257. this._vectors2Arrays[name] = value;
  59258. return this;
  59259. };
  59260. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59261. this._checkUniform(name);
  59262. this._vectors3Arrays[name] = value;
  59263. return this;
  59264. };
  59265. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59266. if (!mesh) {
  59267. return true;
  59268. }
  59269. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59270. return false;
  59271. }
  59272. return false;
  59273. };
  59274. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59275. var scene = this.getScene();
  59276. var engine = scene.getEngine();
  59277. if (!this.checkReadyOnEveryCall) {
  59278. if (this._renderId === scene.getRenderId()) {
  59279. if (this._checkCache(scene, mesh, useInstances)) {
  59280. return true;
  59281. }
  59282. }
  59283. }
  59284. // Instances
  59285. var defines = [];
  59286. var attribs = [];
  59287. var fallbacks = new BABYLON.EffectFallbacks();
  59288. if (useInstances) {
  59289. defines.push("#define INSTANCES");
  59290. }
  59291. for (var index = 0; index < this._options.defines.length; index++) {
  59292. defines.push(this._options.defines[index]);
  59293. }
  59294. for (var index = 0; index < this._options.attributes.length; index++) {
  59295. attribs.push(this._options.attributes[index]);
  59296. }
  59297. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59298. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59299. defines.push("#define VERTEXCOLOR");
  59300. }
  59301. // Bones
  59302. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59303. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59304. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59305. if (mesh.numBoneInfluencers > 4) {
  59306. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59307. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59308. }
  59309. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59310. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59311. fallbacks.addCPUSkinningFallback(0, mesh);
  59312. if (this._options.uniforms.indexOf("mBones") === -1) {
  59313. this._options.uniforms.push("mBones");
  59314. }
  59315. }
  59316. else {
  59317. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59318. }
  59319. // Textures
  59320. for (var name in this._textures) {
  59321. if (!this._textures[name].isReady()) {
  59322. return false;
  59323. }
  59324. }
  59325. // Alpha test
  59326. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59327. defines.push("#define ALPHATEST");
  59328. }
  59329. var previousEffect = this._effect;
  59330. var join = defines.join("\n");
  59331. this._effect = engine.createEffect(this._shaderPath, {
  59332. attributes: attribs,
  59333. uniformsNames: this._options.uniforms,
  59334. uniformBuffersNames: this._options.uniformBuffers,
  59335. samplers: this._options.samplers,
  59336. defines: join,
  59337. fallbacks: fallbacks,
  59338. onCompiled: this.onCompiled,
  59339. onError: this.onError
  59340. }, engine);
  59341. if (!this._effect.isReady()) {
  59342. return false;
  59343. }
  59344. if (previousEffect !== this._effect) {
  59345. scene.resetCachedMaterial();
  59346. }
  59347. this._renderId = scene.getRenderId();
  59348. return true;
  59349. };
  59350. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59351. var scene = this.getScene();
  59352. if (!this._effect) {
  59353. return;
  59354. }
  59355. if (this._options.uniforms.indexOf("world") !== -1) {
  59356. this._effect.setMatrix("world", world);
  59357. }
  59358. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59359. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59360. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59361. }
  59362. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59363. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59364. }
  59365. };
  59366. ShaderMaterial.prototype.bind = function (world, mesh) {
  59367. // Std values
  59368. this.bindOnlyWorldMatrix(world);
  59369. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59370. if (this._options.uniforms.indexOf("view") !== -1) {
  59371. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59372. }
  59373. if (this._options.uniforms.indexOf("projection") !== -1) {
  59374. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59375. }
  59376. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59377. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59378. }
  59379. // Bones
  59380. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59381. var name;
  59382. // Texture
  59383. for (name in this._textures) {
  59384. this._effect.setTexture(name, this._textures[name]);
  59385. }
  59386. // Texture arrays
  59387. for (name in this._textureArrays) {
  59388. this._effect.setTextureArray(name, this._textureArrays[name]);
  59389. }
  59390. // Int
  59391. for (name in this._ints) {
  59392. this._effect.setInt(name, this._ints[name]);
  59393. }
  59394. // Float
  59395. for (name in this._floats) {
  59396. this._effect.setFloat(name, this._floats[name]);
  59397. }
  59398. // Floats
  59399. for (name in this._floatsArrays) {
  59400. this._effect.setArray(name, this._floatsArrays[name]);
  59401. }
  59402. // Color3
  59403. for (name in this._colors3) {
  59404. this._effect.setColor3(name, this._colors3[name]);
  59405. }
  59406. for (name in this._colors3Arrays) {
  59407. this._effect.setArray3(name, this._colors3Arrays[name]);
  59408. }
  59409. // Color4
  59410. for (name in this._colors4) {
  59411. var color = this._colors4[name];
  59412. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59413. }
  59414. // Vector2
  59415. for (name in this._vectors2) {
  59416. this._effect.setVector2(name, this._vectors2[name]);
  59417. }
  59418. // Vector3
  59419. for (name in this._vectors3) {
  59420. this._effect.setVector3(name, this._vectors3[name]);
  59421. }
  59422. // Vector4
  59423. for (name in this._vectors4) {
  59424. this._effect.setVector4(name, this._vectors4[name]);
  59425. }
  59426. // Matrix
  59427. for (name in this._matrices) {
  59428. this._effect.setMatrix(name, this._matrices[name]);
  59429. }
  59430. // Matrix 3x3
  59431. for (name in this._matrices3x3) {
  59432. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59433. }
  59434. // Matrix 2x2
  59435. for (name in this._matrices2x2) {
  59436. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59437. }
  59438. // Vector2Array
  59439. for (name in this._vectors2Arrays) {
  59440. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59441. }
  59442. // Vector3Array
  59443. for (name in this._vectors3Arrays) {
  59444. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59445. }
  59446. }
  59447. this._afterBind(mesh);
  59448. };
  59449. ShaderMaterial.prototype.getActiveTextures = function () {
  59450. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59451. for (var name in this._textures) {
  59452. activeTextures.push(this._textures[name]);
  59453. }
  59454. for (var name in this._textureArrays) {
  59455. var array = this._textureArrays[name];
  59456. for (var index = 0; index < array.length; index++) {
  59457. activeTextures.push(array[index]);
  59458. }
  59459. }
  59460. return activeTextures;
  59461. };
  59462. ShaderMaterial.prototype.hasTexture = function (texture) {
  59463. if (_super.prototype.hasTexture.call(this, texture)) {
  59464. return true;
  59465. }
  59466. for (var name in this._textures) {
  59467. if (this._textures[name] === texture) {
  59468. return true;
  59469. }
  59470. }
  59471. for (var name in this._textureArrays) {
  59472. var array = this._textureArrays[name];
  59473. for (var index = 0; index < array.length; index++) {
  59474. if (array[index] === texture) {
  59475. return true;
  59476. }
  59477. }
  59478. }
  59479. return false;
  59480. };
  59481. ShaderMaterial.prototype.clone = function (name) {
  59482. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59483. return newShaderMaterial;
  59484. };
  59485. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59486. if (forceDisposeTextures) {
  59487. var name;
  59488. for (name in this._textures) {
  59489. this._textures[name].dispose();
  59490. }
  59491. for (name in this._textureArrays) {
  59492. var array = this._textureArrays[name];
  59493. for (var index = 0; index < array.length; index++) {
  59494. array[index].dispose();
  59495. }
  59496. }
  59497. }
  59498. this._textures = {};
  59499. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59500. };
  59501. ShaderMaterial.prototype.serialize = function () {
  59502. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59503. serializationObject.customType = "BABYLON.ShaderMaterial";
  59504. serializationObject.options = this._options;
  59505. serializationObject.shaderPath = this._shaderPath;
  59506. var name;
  59507. // Texture
  59508. serializationObject.textures = {};
  59509. for (name in this._textures) {
  59510. serializationObject.textures[name] = this._textures[name].serialize();
  59511. }
  59512. // Texture arrays
  59513. serializationObject.textureArrays = {};
  59514. for (name in this._textureArrays) {
  59515. serializationObject.textureArrays[name] = [];
  59516. var array = this._textureArrays[name];
  59517. for (var index = 0; index < array.length; index++) {
  59518. serializationObject.textureArrays[name].push(array[index].serialize());
  59519. }
  59520. }
  59521. // Float
  59522. serializationObject.floats = {};
  59523. for (name in this._floats) {
  59524. serializationObject.floats[name] = this._floats[name];
  59525. }
  59526. // Float s
  59527. serializationObject.FloatArrays = {};
  59528. for (name in this._floatsArrays) {
  59529. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59530. }
  59531. // Color3
  59532. serializationObject.colors3 = {};
  59533. for (name in this._colors3) {
  59534. serializationObject.colors3[name] = this._colors3[name].asArray();
  59535. }
  59536. // Color3 array
  59537. serializationObject.colors3Arrays = {};
  59538. for (name in this._colors3Arrays) {
  59539. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59540. }
  59541. // Color4
  59542. serializationObject.colors4 = {};
  59543. for (name in this._colors4) {
  59544. serializationObject.colors4[name] = this._colors4[name].asArray();
  59545. }
  59546. // Vector2
  59547. serializationObject.vectors2 = {};
  59548. for (name in this._vectors2) {
  59549. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59550. }
  59551. // Vector3
  59552. serializationObject.vectors3 = {};
  59553. for (name in this._vectors3) {
  59554. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59555. }
  59556. // Vector4
  59557. serializationObject.vectors4 = {};
  59558. for (name in this._vectors4) {
  59559. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59560. }
  59561. // Matrix
  59562. serializationObject.matrices = {};
  59563. for (name in this._matrices) {
  59564. serializationObject.matrices[name] = this._matrices[name].asArray();
  59565. }
  59566. // Matrix 3x3
  59567. serializationObject.matrices3x3 = {};
  59568. for (name in this._matrices3x3) {
  59569. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59570. }
  59571. // Matrix 2x2
  59572. serializationObject.matrices2x2 = {};
  59573. for (name in this._matrices2x2) {
  59574. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59575. }
  59576. // Vector2Array
  59577. serializationObject.vectors2Arrays = {};
  59578. for (name in this._vectors2Arrays) {
  59579. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59580. }
  59581. // Vector3Array
  59582. serializationObject.vectors3Arrays = {};
  59583. for (name in this._vectors3Arrays) {
  59584. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59585. }
  59586. return serializationObject;
  59587. };
  59588. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59589. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59590. var name;
  59591. // Texture
  59592. for (name in source.textures) {
  59593. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59594. }
  59595. // Texture arrays
  59596. for (name in source.textureArrays) {
  59597. var array = source.textureArrays[name];
  59598. var textureArray = new Array();
  59599. for (var index = 0; index < array.length; index++) {
  59600. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59601. }
  59602. material.setTextureArray(name, textureArray);
  59603. }
  59604. // Float
  59605. for (name in source.floats) {
  59606. material.setFloat(name, source.floats[name]);
  59607. }
  59608. // Float s
  59609. for (name in source.floatsArrays) {
  59610. material.setFloats(name, source.floatsArrays[name]);
  59611. }
  59612. // Color3
  59613. for (name in source.colors3) {
  59614. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59615. }
  59616. // Color3 arrays
  59617. for (name in source.colors3Arrays) {
  59618. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59619. if (i % 3 === 0) {
  59620. arr.push([num]);
  59621. }
  59622. else {
  59623. arr[arr.length - 1].push(num);
  59624. }
  59625. return arr;
  59626. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59627. material.setColor3Array(name, colors);
  59628. }
  59629. // Color4
  59630. for (name in source.colors4) {
  59631. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59632. }
  59633. // Vector2
  59634. for (name in source.vectors2) {
  59635. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59636. }
  59637. // Vector3
  59638. for (name in source.vectors3) {
  59639. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59640. }
  59641. // Vector4
  59642. for (name in source.vectors4) {
  59643. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59644. }
  59645. // Matrix
  59646. for (name in source.matrices) {
  59647. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59648. }
  59649. // Matrix 3x3
  59650. for (name in source.matrices3x3) {
  59651. material.setMatrix3x3(name, source.matrices3x3[name]);
  59652. }
  59653. // Matrix 2x2
  59654. for (name in source.matrices2x2) {
  59655. material.setMatrix2x2(name, source.matrices2x2[name]);
  59656. }
  59657. // Vector2Array
  59658. for (name in source.vectors2Arrays) {
  59659. material.setArray2(name, source.vectors2Arrays[name]);
  59660. }
  59661. // Vector3Array
  59662. for (name in source.vectors3Arrays) {
  59663. material.setArray3(name, source.vectors3Arrays[name]);
  59664. }
  59665. return material;
  59666. };
  59667. return ShaderMaterial;
  59668. }(BABYLON.Material));
  59669. BABYLON.ShaderMaterial = ShaderMaterial;
  59670. })(BABYLON || (BABYLON = {}));
  59671. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59672. var BABYLON;
  59673. (function (BABYLON) {
  59674. var GroundMesh = /** @class */ (function (_super) {
  59675. __extends(GroundMesh, _super);
  59676. function GroundMesh(name, scene) {
  59677. var _this = _super.call(this, name, scene) || this;
  59678. _this.generateOctree = false;
  59679. return _this;
  59680. }
  59681. GroundMesh.prototype.getClassName = function () {
  59682. return "GroundMesh";
  59683. };
  59684. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59685. get: function () {
  59686. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59687. },
  59688. enumerable: true,
  59689. configurable: true
  59690. });
  59691. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59692. get: function () {
  59693. return this._subdivisionsX;
  59694. },
  59695. enumerable: true,
  59696. configurable: true
  59697. });
  59698. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59699. get: function () {
  59700. return this._subdivisionsY;
  59701. },
  59702. enumerable: true,
  59703. configurable: true
  59704. });
  59705. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59706. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59707. this._subdivisionsX = chunksCount;
  59708. this._subdivisionsY = chunksCount;
  59709. this.subdivide(chunksCount);
  59710. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59711. };
  59712. /**
  59713. * Returns a height (y) value in the Worl system :
  59714. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59715. * Returns the ground y position if (x, z) are outside the ground surface.
  59716. */
  59717. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59718. var world = this.getWorldMatrix();
  59719. var invMat = BABYLON.Tmp.Matrix[5];
  59720. world.invertToRef(invMat);
  59721. var tmpVect = BABYLON.Tmp.Vector3[8];
  59722. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59723. x = tmpVect.x;
  59724. z = tmpVect.z;
  59725. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59726. return this.position.y;
  59727. }
  59728. if (!this._heightQuads || this._heightQuads.length == 0) {
  59729. this._initHeightQuads();
  59730. this._computeHeightQuads();
  59731. }
  59732. var facet = this._getFacetAt(x, z);
  59733. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59734. // return y in the World system
  59735. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59736. return tmpVect.y;
  59737. };
  59738. /**
  59739. * Returns a normalized vector (Vector3) orthogonal to the ground
  59740. * at the ground coordinates (x, z) expressed in the World system.
  59741. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59742. */
  59743. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59744. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59745. this.getNormalAtCoordinatesToRef(x, z, normal);
  59746. return normal;
  59747. };
  59748. /**
  59749. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59750. * at the ground coordinates (x, z) expressed in the World system.
  59751. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59752. * Returns the GroundMesh.
  59753. */
  59754. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59755. var world = this.getWorldMatrix();
  59756. var tmpMat = BABYLON.Tmp.Matrix[5];
  59757. world.invertToRef(tmpMat);
  59758. var tmpVect = BABYLON.Tmp.Vector3[8];
  59759. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59760. x = tmpVect.x;
  59761. z = tmpVect.z;
  59762. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59763. return this;
  59764. }
  59765. if (!this._heightQuads || this._heightQuads.length == 0) {
  59766. this._initHeightQuads();
  59767. this._computeHeightQuads();
  59768. }
  59769. var facet = this._getFacetAt(x, z);
  59770. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59771. return this;
  59772. };
  59773. /**
  59774. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59775. * if the ground has been updated.
  59776. * This can be used in the render loop.
  59777. * Returns the GroundMesh.
  59778. */
  59779. GroundMesh.prototype.updateCoordinateHeights = function () {
  59780. if (!this._heightQuads || this._heightQuads.length == 0) {
  59781. this._initHeightQuads();
  59782. }
  59783. this._computeHeightQuads();
  59784. return this;
  59785. };
  59786. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59787. GroundMesh.prototype._getFacetAt = function (x, z) {
  59788. // retrieve col and row from x, z coordinates in the ground local system
  59789. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59790. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59791. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59792. var facet;
  59793. if (z < quad.slope.x * x + quad.slope.y) {
  59794. facet = quad.facet1;
  59795. }
  59796. else {
  59797. facet = quad.facet2;
  59798. }
  59799. return facet;
  59800. };
  59801. // Creates and populates the heightMap array with "facet" elements :
  59802. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59803. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59804. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59805. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59806. // Returns the GroundMesh.
  59807. GroundMesh.prototype._initHeightQuads = function () {
  59808. var subdivisionsX = this._subdivisionsX;
  59809. var subdivisionsY = this._subdivisionsY;
  59810. this._heightQuads = new Array();
  59811. for (var row = 0; row < subdivisionsY; row++) {
  59812. for (var col = 0; col < subdivisionsX; col++) {
  59813. 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) };
  59814. this._heightQuads[row * subdivisionsX + col] = quad;
  59815. }
  59816. }
  59817. return this;
  59818. };
  59819. // Compute each quad element values and update the the heightMap array :
  59820. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59821. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59822. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59823. // Returns the GroundMesh.
  59824. GroundMesh.prototype._computeHeightQuads = function () {
  59825. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59826. if (!positions) {
  59827. return this;
  59828. }
  59829. var v1 = BABYLON.Tmp.Vector3[3];
  59830. var v2 = BABYLON.Tmp.Vector3[2];
  59831. var v3 = BABYLON.Tmp.Vector3[1];
  59832. var v4 = BABYLON.Tmp.Vector3[0];
  59833. var v1v2 = BABYLON.Tmp.Vector3[4];
  59834. var v1v3 = BABYLON.Tmp.Vector3[5];
  59835. var v1v4 = BABYLON.Tmp.Vector3[6];
  59836. var norm1 = BABYLON.Tmp.Vector3[7];
  59837. var norm2 = BABYLON.Tmp.Vector3[8];
  59838. var i = 0;
  59839. var j = 0;
  59840. var k = 0;
  59841. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59842. var h = 0;
  59843. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59844. var d2 = 0;
  59845. var subdivisionsX = this._subdivisionsX;
  59846. var subdivisionsY = this._subdivisionsY;
  59847. for (var row = 0; row < subdivisionsY; row++) {
  59848. for (var col = 0; col < subdivisionsX; col++) {
  59849. i = col * 3;
  59850. j = row * (subdivisionsX + 1) * 3;
  59851. k = (row + 1) * (subdivisionsX + 1) * 3;
  59852. v1.x = positions[j + i];
  59853. v1.y = positions[j + i + 1];
  59854. v1.z = positions[j + i + 2];
  59855. v2.x = positions[j + i + 3];
  59856. v2.y = positions[j + i + 4];
  59857. v2.z = positions[j + i + 5];
  59858. v3.x = positions[k + i];
  59859. v3.y = positions[k + i + 1];
  59860. v3.z = positions[k + i + 2];
  59861. v4.x = positions[k + i + 3];
  59862. v4.y = positions[k + i + 4];
  59863. v4.z = positions[k + i + 5];
  59864. // 2D slope V1V4
  59865. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59866. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59867. // facet equations :
  59868. // we compute each facet normal vector
  59869. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59870. // we compute the value d by applying the equation to v1 which belongs to the plane
  59871. // then we store the facet equation in a Vector4
  59872. v2.subtractToRef(v1, v1v2);
  59873. v3.subtractToRef(v1, v1v3);
  59874. v4.subtractToRef(v1, v1v4);
  59875. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59876. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59877. norm1.normalize();
  59878. norm2.normalize();
  59879. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59880. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59881. var quad = this._heightQuads[row * subdivisionsX + col];
  59882. quad.slope.copyFromFloats(cd, h);
  59883. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59884. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59885. }
  59886. }
  59887. return this;
  59888. };
  59889. GroundMesh.prototype.serialize = function (serializationObject) {
  59890. _super.prototype.serialize.call(this, serializationObject);
  59891. serializationObject.subdivisionsX = this._subdivisionsX;
  59892. serializationObject.subdivisionsY = this._subdivisionsY;
  59893. serializationObject.minX = this._minX;
  59894. serializationObject.maxX = this._maxX;
  59895. serializationObject.minZ = this._minZ;
  59896. serializationObject.maxZ = this._maxZ;
  59897. serializationObject.width = this._width;
  59898. serializationObject.height = this._height;
  59899. };
  59900. GroundMesh.Parse = function (parsedMesh, scene) {
  59901. var result = new GroundMesh(parsedMesh.name, scene);
  59902. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59903. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59904. result._minX = parsedMesh.minX;
  59905. result._maxX = parsedMesh.maxX;
  59906. result._minZ = parsedMesh.minZ;
  59907. result._maxZ = parsedMesh.maxZ;
  59908. result._width = parsedMesh.width;
  59909. result._height = parsedMesh.height;
  59910. return result;
  59911. };
  59912. return GroundMesh;
  59913. }(BABYLON.Mesh));
  59914. BABYLON.GroundMesh = GroundMesh;
  59915. })(BABYLON || (BABYLON = {}));
  59916. //# sourceMappingURL=babylon.groundMesh.js.map
  59917. var BABYLON;
  59918. (function (BABYLON) {
  59919. /**
  59920. * Creates an instance based on a source mesh.
  59921. */
  59922. var InstancedMesh = /** @class */ (function (_super) {
  59923. __extends(InstancedMesh, _super);
  59924. function InstancedMesh(name, source) {
  59925. var _this = _super.call(this, name, source.getScene()) || this;
  59926. source.instances.push(_this);
  59927. _this._sourceMesh = source;
  59928. _this.position.copyFrom(source.position);
  59929. _this.rotation.copyFrom(source.rotation);
  59930. _this.scaling.copyFrom(source.scaling);
  59931. if (source.rotationQuaternion) {
  59932. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59933. }
  59934. _this.infiniteDistance = source.infiniteDistance;
  59935. _this.setPivotMatrix(source.getPivotMatrix());
  59936. _this.refreshBoundingInfo();
  59937. _this._syncSubMeshes();
  59938. return _this;
  59939. }
  59940. /**
  59941. * Returns the string "InstancedMesh".
  59942. */
  59943. InstancedMesh.prototype.getClassName = function () {
  59944. return "InstancedMesh";
  59945. };
  59946. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59947. // Methods
  59948. get: function () {
  59949. return this._sourceMesh.receiveShadows;
  59950. },
  59951. enumerable: true,
  59952. configurable: true
  59953. });
  59954. Object.defineProperty(InstancedMesh.prototype, "material", {
  59955. get: function () {
  59956. return this._sourceMesh.material;
  59957. },
  59958. enumerable: true,
  59959. configurable: true
  59960. });
  59961. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59962. get: function () {
  59963. return this._sourceMesh.visibility;
  59964. },
  59965. enumerable: true,
  59966. configurable: true
  59967. });
  59968. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59969. get: function () {
  59970. return this._sourceMesh.skeleton;
  59971. },
  59972. enumerable: true,
  59973. configurable: true
  59974. });
  59975. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59976. get: function () {
  59977. return this._sourceMesh.renderingGroupId;
  59978. },
  59979. set: function (value) {
  59980. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59981. return;
  59982. }
  59983. //no-op with warning
  59984. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59985. },
  59986. enumerable: true,
  59987. configurable: true
  59988. });
  59989. /**
  59990. * Returns the total number of vertices (integer).
  59991. */
  59992. InstancedMesh.prototype.getTotalVertices = function () {
  59993. return this._sourceMesh.getTotalVertices();
  59994. };
  59995. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59996. get: function () {
  59997. return this._sourceMesh;
  59998. },
  59999. enumerable: true,
  60000. configurable: true
  60001. });
  60002. /**
  60003. * Is this node ready to be used/rendered
  60004. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60005. * @return {boolean} is it ready
  60006. */
  60007. InstancedMesh.prototype.isReady = function (completeCheck) {
  60008. if (completeCheck === void 0) { completeCheck = false; }
  60009. return this._sourceMesh.isReady(completeCheck, true);
  60010. };
  60011. /**
  60012. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60013. */
  60014. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60015. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60016. };
  60017. /**
  60018. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60019. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60020. * The `data` are either a numeric array either a Float32Array.
  60021. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60022. * 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).
  60023. * Note that a new underlying VertexBuffer object is created each call.
  60024. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60025. *
  60026. * Possible `kind` values :
  60027. * - BABYLON.VertexBuffer.PositionKind
  60028. * - BABYLON.VertexBuffer.UVKind
  60029. * - BABYLON.VertexBuffer.UV2Kind
  60030. * - BABYLON.VertexBuffer.UV3Kind
  60031. * - BABYLON.VertexBuffer.UV4Kind
  60032. * - BABYLON.VertexBuffer.UV5Kind
  60033. * - BABYLON.VertexBuffer.UV6Kind
  60034. * - BABYLON.VertexBuffer.ColorKind
  60035. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60036. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60037. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60038. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60039. *
  60040. * Returns the Mesh.
  60041. */
  60042. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60043. if (this.sourceMesh) {
  60044. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60045. }
  60046. return this.sourceMesh;
  60047. };
  60048. /**
  60049. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60050. * If the mesh has no geometry, it is simply returned as it is.
  60051. * The `data` are either a numeric array either a Float32Array.
  60052. * No new underlying VertexBuffer object is created.
  60053. * 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.
  60054. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60055. *
  60056. * Possible `kind` values :
  60057. * - BABYLON.VertexBuffer.PositionKind
  60058. * - BABYLON.VertexBuffer.UVKind
  60059. * - BABYLON.VertexBuffer.UV2Kind
  60060. * - BABYLON.VertexBuffer.UV3Kind
  60061. * - BABYLON.VertexBuffer.UV4Kind
  60062. * - BABYLON.VertexBuffer.UV5Kind
  60063. * - BABYLON.VertexBuffer.UV6Kind
  60064. * - BABYLON.VertexBuffer.ColorKind
  60065. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60066. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60067. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60068. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60069. *
  60070. * Returns the Mesh.
  60071. */
  60072. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60073. if (this.sourceMesh) {
  60074. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60075. }
  60076. return this.sourceMesh;
  60077. };
  60078. /**
  60079. * Sets the mesh indices.
  60080. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60081. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60082. * This method creates a new index buffer each call.
  60083. * Returns the Mesh.
  60084. */
  60085. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60086. if (totalVertices === void 0) { totalVertices = null; }
  60087. if (this.sourceMesh) {
  60088. this.sourceMesh.setIndices(indices, totalVertices);
  60089. }
  60090. return this.sourceMesh;
  60091. };
  60092. /**
  60093. * Boolean : True if the mesh owns the requested kind of data.
  60094. */
  60095. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60096. return this._sourceMesh.isVerticesDataPresent(kind);
  60097. };
  60098. /**
  60099. * Returns an array of indices (IndicesArray).
  60100. */
  60101. InstancedMesh.prototype.getIndices = function () {
  60102. return this._sourceMesh.getIndices();
  60103. };
  60104. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60105. get: function () {
  60106. return this._sourceMesh._positions;
  60107. },
  60108. enumerable: true,
  60109. configurable: true
  60110. });
  60111. /**
  60112. * Sets a new updated BoundingInfo to the mesh.
  60113. * Returns the mesh.
  60114. */
  60115. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60116. var meshBB = this._sourceMesh.getBoundingInfo();
  60117. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60118. this._updateBoundingInfo();
  60119. return this;
  60120. };
  60121. InstancedMesh.prototype._preActivate = function () {
  60122. if (this._currentLOD) {
  60123. this._currentLOD._preActivate();
  60124. }
  60125. return this;
  60126. };
  60127. InstancedMesh.prototype._activate = function (renderId) {
  60128. if (this._currentLOD) {
  60129. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60130. }
  60131. return this;
  60132. };
  60133. /**
  60134. * Returns the current associated LOD AbstractMesh.
  60135. */
  60136. InstancedMesh.prototype.getLOD = function (camera) {
  60137. if (!camera) {
  60138. return this;
  60139. }
  60140. var boundingInfo = this.getBoundingInfo();
  60141. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60142. if (this._currentLOD === this.sourceMesh) {
  60143. return this;
  60144. }
  60145. return this._currentLOD;
  60146. };
  60147. InstancedMesh.prototype._syncSubMeshes = function () {
  60148. this.releaseSubMeshes();
  60149. if (this._sourceMesh.subMeshes) {
  60150. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60151. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60152. }
  60153. }
  60154. return this;
  60155. };
  60156. InstancedMesh.prototype._generatePointsArray = function () {
  60157. return this._sourceMesh._generatePointsArray();
  60158. };
  60159. /**
  60160. * Creates a new InstancedMesh from the current mesh.
  60161. * - name (string) : the cloned mesh name
  60162. * - newParent (optional Node) : the optional Node to parent the clone to.
  60163. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60164. *
  60165. * Returns the clone.
  60166. */
  60167. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60168. var result = this._sourceMesh.createInstance(name);
  60169. // Deep copy
  60170. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60171. // Bounding info
  60172. this.refreshBoundingInfo();
  60173. // Parent
  60174. if (newParent) {
  60175. result.parent = newParent;
  60176. }
  60177. if (!doNotCloneChildren) {
  60178. // Children
  60179. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60180. var mesh = this.getScene().meshes[index];
  60181. if (mesh.parent === this) {
  60182. mesh.clone(mesh.name, result);
  60183. }
  60184. }
  60185. }
  60186. result.computeWorldMatrix(true);
  60187. return result;
  60188. };
  60189. /**
  60190. * Disposes the InstancedMesh.
  60191. * Returns nothing.
  60192. */
  60193. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60194. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60195. // Remove from mesh
  60196. var index = this._sourceMesh.instances.indexOf(this);
  60197. this._sourceMesh.instances.splice(index, 1);
  60198. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60199. };
  60200. return InstancedMesh;
  60201. }(BABYLON.AbstractMesh));
  60202. BABYLON.InstancedMesh = InstancedMesh;
  60203. })(BABYLON || (BABYLON = {}));
  60204. //# sourceMappingURL=babylon.instancedMesh.js.map
  60205. var BABYLON;
  60206. (function (BABYLON) {
  60207. var LinesMesh = /** @class */ (function (_super) {
  60208. __extends(LinesMesh, _super);
  60209. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60210. if (scene === void 0) { scene = null; }
  60211. if (parent === void 0) { parent = null; }
  60212. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60213. _this.useVertexColor = useVertexColor;
  60214. _this.useVertexAlpha = useVertexAlpha;
  60215. _this.color = new BABYLON.Color3(1, 1, 1);
  60216. _this.alpha = 1;
  60217. if (source) {
  60218. _this.color = source.color.clone();
  60219. _this.alpha = source.alpha;
  60220. _this.useVertexColor = source.useVertexColor;
  60221. _this.useVertexAlpha = source.useVertexAlpha;
  60222. }
  60223. _this._intersectionThreshold = 0.1;
  60224. var defines = [];
  60225. var options = {
  60226. attributes: [BABYLON.VertexBuffer.PositionKind],
  60227. uniforms: ["world", "viewProjection"],
  60228. needAlphaBlending: true,
  60229. defines: defines
  60230. };
  60231. if (useVertexAlpha === false) {
  60232. options.needAlphaBlending = false;
  60233. }
  60234. if (!useVertexColor) {
  60235. options.uniforms.push("color");
  60236. }
  60237. else {
  60238. options.defines.push("#define VERTEXCOLOR");
  60239. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60240. }
  60241. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60242. return _this;
  60243. }
  60244. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60245. /**
  60246. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60247. * This margin is expressed in world space coordinates, so its value may vary.
  60248. * Default value is 0.1
  60249. * @returns the intersection Threshold value.
  60250. */
  60251. get: function () {
  60252. return this._intersectionThreshold;
  60253. },
  60254. /**
  60255. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60256. * This margin is expressed in world space coordinates, so its value may vary.
  60257. * @param value the new threshold to apply
  60258. */
  60259. set: function (value) {
  60260. if (this._intersectionThreshold === value) {
  60261. return;
  60262. }
  60263. this._intersectionThreshold = value;
  60264. if (this.geometry) {
  60265. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60266. }
  60267. },
  60268. enumerable: true,
  60269. configurable: true
  60270. });
  60271. /**
  60272. * Returns the string "LineMesh"
  60273. */
  60274. LinesMesh.prototype.getClassName = function () {
  60275. return "LinesMesh";
  60276. };
  60277. Object.defineProperty(LinesMesh.prototype, "material", {
  60278. get: function () {
  60279. return this._colorShader;
  60280. },
  60281. set: function (value) {
  60282. // Do nothing
  60283. },
  60284. enumerable: true,
  60285. configurable: true
  60286. });
  60287. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60288. get: function () {
  60289. return false;
  60290. },
  60291. enumerable: true,
  60292. configurable: true
  60293. });
  60294. LinesMesh.prototype.createInstance = function (name) {
  60295. throw new Error("LinesMeshes do not support createInstance.");
  60296. };
  60297. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60298. if (!this._geometry) {
  60299. return this;
  60300. }
  60301. // VBOs
  60302. this._geometry._bind(this._colorShader.getEffect());
  60303. // Color
  60304. if (!this.useVertexColor) {
  60305. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60306. }
  60307. return this;
  60308. };
  60309. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60310. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60311. return this;
  60312. }
  60313. var engine = this.getScene().getEngine();
  60314. // Draw order
  60315. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60316. return this;
  60317. };
  60318. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60319. this._colorShader.dispose();
  60320. _super.prototype.dispose.call(this, doNotRecurse);
  60321. };
  60322. /**
  60323. * Returns a new LineMesh object cloned from the current one.
  60324. */
  60325. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60326. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60327. };
  60328. return LinesMesh;
  60329. }(BABYLON.Mesh));
  60330. BABYLON.LinesMesh = LinesMesh;
  60331. })(BABYLON || (BABYLON = {}));
  60332. //# sourceMappingURL=babylon.linesMesh.js.map
  60333. var BABYLON;
  60334. (function (BABYLON) {
  60335. /**
  60336. * Class containing static functions to help procedurally build meshes
  60337. */
  60338. var MeshBuilder = /** @class */ (function () {
  60339. function MeshBuilder() {
  60340. }
  60341. MeshBuilder.updateSideOrientation = function (orientation) {
  60342. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60343. return BABYLON.Mesh.DOUBLESIDE;
  60344. }
  60345. if (orientation === undefined || orientation === null) {
  60346. return BABYLON.Mesh.FRONTSIDE;
  60347. }
  60348. return orientation;
  60349. };
  60350. /**
  60351. * Creates a box mesh
  60352. * * The parameter `size` sets the size (float) of each box side (default 1)
  60353. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60354. * * 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)
  60355. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60356. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60357. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60358. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60359. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60360. * @param name defines the name of the mesh
  60361. * @param options defines the options used to create the mesh
  60362. * @param scene defines the hosting scene
  60363. * @returns the box mesh
  60364. */
  60365. MeshBuilder.CreateBox = function (name, options, scene) {
  60366. if (scene === void 0) { scene = null; }
  60367. var box = new BABYLON.Mesh(name, scene);
  60368. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60369. box._originalBuilderSideOrientation = options.sideOrientation;
  60370. var vertexData = BABYLON.VertexData.CreateBox(options);
  60371. vertexData.applyToMesh(box, options.updatable);
  60372. return box;
  60373. };
  60374. /**
  60375. * Creates a sphere mesh
  60376. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60377. * * 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`)
  60378. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60379. * * 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
  60380. * * 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)
  60381. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60382. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60383. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60384. * @param name defines the name of the mesh
  60385. * @param options defines the options used to create the mesh
  60386. * @param scene defines the hosting scene
  60387. * @returns the sphere mesh
  60388. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60389. */
  60390. MeshBuilder.CreateSphere = function (name, options, scene) {
  60391. var sphere = new BABYLON.Mesh(name, scene);
  60392. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60393. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60394. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60395. vertexData.applyToMesh(sphere, options.updatable);
  60396. return sphere;
  60397. };
  60398. /**
  60399. * Creates a plane polygonal mesh. By default, this is a disc
  60400. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60401. * * 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
  60402. * * 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
  60403. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60404. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60405. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60406. * @param name defines the name of the mesh
  60407. * @param options defines the options used to create the mesh
  60408. * @param scene defines the hosting scene
  60409. * @returns the plane polygonal mesh
  60410. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60411. */
  60412. MeshBuilder.CreateDisc = function (name, options, scene) {
  60413. if (scene === void 0) { scene = null; }
  60414. var disc = new BABYLON.Mesh(name, scene);
  60415. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60416. disc._originalBuilderSideOrientation = options.sideOrientation;
  60417. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60418. vertexData.applyToMesh(disc, options.updatable);
  60419. return disc;
  60420. };
  60421. /**
  60422. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60423. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60424. * * 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`)
  60425. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60426. * * 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
  60427. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60428. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60429. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60430. * @param name defines the name of the mesh
  60431. * @param options defines the options used to create the mesh
  60432. * @param scene defines the hosting scene
  60433. * @returns the icosahedron mesh
  60434. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60435. */
  60436. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60437. var sphere = new BABYLON.Mesh(name, scene);
  60438. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60439. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60440. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60441. vertexData.applyToMesh(sphere, options.updatable);
  60442. return sphere;
  60443. };
  60444. ;
  60445. /**
  60446. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60447. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60448. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60449. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60450. * * 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
  60451. * * 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
  60452. * * 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
  60453. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60454. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60455. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60456. * * 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
  60457. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60458. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  60459. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60460. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60461. * @param name defines the name of the mesh
  60462. * @param options defines the options used to create the mesh
  60463. * @param scene defines the hosting scene
  60464. * @returns the ribbon mesh
  60465. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60466. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60467. */
  60468. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60469. if (scene === void 0) { scene = null; }
  60470. var pathArray = options.pathArray;
  60471. var closeArray = options.closeArray;
  60472. var closePath = options.closePath;
  60473. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60474. var instance = options.instance;
  60475. var updatable = options.updatable;
  60476. if (instance) { // existing ribbon instance update
  60477. // positionFunction : ribbon case
  60478. // only pathArray and sideOrientation parameters are taken into account for positions update
  60479. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60480. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60481. var positionFunction = function (positions) {
  60482. var minlg = pathArray[0].length;
  60483. var i = 0;
  60484. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60485. for (var si = 1; si <= ns; si++) {
  60486. for (var p = 0; p < pathArray.length; p++) {
  60487. var path = pathArray[p];
  60488. var l = path.length;
  60489. minlg = (minlg < l) ? minlg : l;
  60490. var j = 0;
  60491. while (j < minlg) {
  60492. positions[i] = path[j].x;
  60493. positions[i + 1] = path[j].y;
  60494. positions[i + 2] = path[j].z;
  60495. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60496. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60497. }
  60498. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60499. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60500. }
  60501. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60502. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60503. }
  60504. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60505. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60506. }
  60507. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60508. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60509. }
  60510. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60511. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60512. }
  60513. j++;
  60514. i += 3;
  60515. }
  60516. if (instance._closePath) {
  60517. positions[i] = path[0].x;
  60518. positions[i + 1] = path[0].y;
  60519. positions[i + 2] = path[0].z;
  60520. i += 3;
  60521. }
  60522. }
  60523. }
  60524. };
  60525. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60526. positionFunction(positions);
  60527. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60528. instance._boundingInfo.update(instance._worldMatrix);
  60529. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60530. if (options.colors) {
  60531. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60532. for (var c = 0; c < options.colors.length; c++) {
  60533. colors[c * 4] = options.colors[c].r;
  60534. colors[c * 4 + 1] = options.colors[c].g;
  60535. colors[c * 4 + 2] = options.colors[c].b;
  60536. colors[c * 4 + 3] = options.colors[c].a;
  60537. }
  60538. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60539. }
  60540. if (options.uvs) {
  60541. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60542. for (var i = 0; i < options.uvs.length; i++) {
  60543. uvs[i * 2] = options.uvs[i].x;
  60544. uvs[i * 2 + 1] = options.uvs[i].y;
  60545. }
  60546. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60547. }
  60548. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60549. var indices = instance.getIndices();
  60550. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60551. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60552. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60553. if (instance._closePath) {
  60554. var indexFirst = 0;
  60555. var indexLast = 0;
  60556. for (var p = 0; p < pathArray.length; p++) {
  60557. indexFirst = instance._idx[p] * 3;
  60558. if (p + 1 < pathArray.length) {
  60559. indexLast = (instance._idx[p + 1] - 1) * 3;
  60560. }
  60561. else {
  60562. indexLast = normals.length - 3;
  60563. }
  60564. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60565. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60566. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60567. normals[indexLast] = normals[indexFirst];
  60568. normals[indexLast + 1] = normals[indexFirst + 1];
  60569. normals[indexLast + 2] = normals[indexFirst + 2];
  60570. }
  60571. }
  60572. if (!(instance.areNormalsFrozen)) {
  60573. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60574. }
  60575. }
  60576. return instance;
  60577. }
  60578. else { // new ribbon creation
  60579. var ribbon = new BABYLON.Mesh(name, scene);
  60580. ribbon._originalBuilderSideOrientation = sideOrientation;
  60581. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60582. if (closePath) {
  60583. ribbon._idx = vertexData._idx;
  60584. }
  60585. ribbon._closePath = closePath;
  60586. ribbon._closeArray = closeArray;
  60587. vertexData.applyToMesh(ribbon, updatable);
  60588. return ribbon;
  60589. }
  60590. };
  60591. /**
  60592. * Creates a cylinder or a cone mesh
  60593. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60594. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60595. * * 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.
  60596. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60597. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60598. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60599. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60600. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60601. * * 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).
  60602. * * 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
  60603. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60604. * * 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
  60605. * * 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.
  60606. * * If `enclose` is false, a ring surface is one element.
  60607. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60608. * * 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
  60609. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60610. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60611. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60612. * @param name defines the name of the mesh
  60613. * @param options defines the options used to create the mesh
  60614. * @param scene defines the hosting scene
  60615. * @returns the cylinder mesh
  60616. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60617. */
  60618. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60619. var cylinder = new BABYLON.Mesh(name, scene);
  60620. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60621. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60622. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60623. vertexData.applyToMesh(cylinder, options.updatable);
  60624. return cylinder;
  60625. };
  60626. /**
  60627. * Creates a torus mesh
  60628. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60629. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60630. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60631. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60632. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60633. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60634. * @param name defines the name of the mesh
  60635. * @param options defines the options used to create the mesh
  60636. * @param scene defines the hosting scene
  60637. * @returns the torus mesh
  60638. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60639. */
  60640. MeshBuilder.CreateTorus = function (name, options, scene) {
  60641. var torus = new BABYLON.Mesh(name, scene);
  60642. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60643. torus._originalBuilderSideOrientation = options.sideOrientation;
  60644. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60645. vertexData.applyToMesh(torus, options.updatable);
  60646. return torus;
  60647. };
  60648. /**
  60649. * Creates a torus knot mesh
  60650. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60651. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60652. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60653. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60654. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60655. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60656. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60657. * @param name defines the name of the mesh
  60658. * @param options defines the options used to create the mesh
  60659. * @param scene defines the hosting scene
  60660. * @returns the torus knot mesh
  60661. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60662. */
  60663. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60664. var torusKnot = new BABYLON.Mesh(name, scene);
  60665. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60666. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60667. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60668. vertexData.applyToMesh(torusKnot, options.updatable);
  60669. return torusKnot;
  60670. };
  60671. /**
  60672. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60673. * * 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
  60674. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60675. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60676. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60677. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60678. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60679. * * 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
  60680. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60681. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60682. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60683. * @param name defines the name of the new line system
  60684. * @param options defines the options used to create the line system
  60685. * @param scene defines the hosting scene
  60686. * @returns a new line system mesh
  60687. */
  60688. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60689. var instance = options.instance;
  60690. var lines = options.lines;
  60691. var colors = options.colors;
  60692. if (instance) { // lines update
  60693. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60694. var vertexColor;
  60695. var lineColors;
  60696. if (colors) {
  60697. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60698. }
  60699. var i = 0;
  60700. var c = 0;
  60701. for (var l = 0; l < lines.length; l++) {
  60702. var points = lines[l];
  60703. for (var p = 0; p < points.length; p++) {
  60704. positions[i] = points[p].x;
  60705. positions[i + 1] = points[p].y;
  60706. positions[i + 2] = points[p].z;
  60707. if (colors && vertexColor) {
  60708. lineColors = colors[l];
  60709. vertexColor[c] = lineColors[p].r;
  60710. vertexColor[c + 1] = lineColors[p].g;
  60711. vertexColor[c + 2] = lineColors[p].b;
  60712. vertexColor[c + 3] = lineColors[p].a;
  60713. c += 4;
  60714. }
  60715. i += 3;
  60716. }
  60717. }
  60718. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60719. if (colors && vertexColor) {
  60720. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60721. }
  60722. return instance;
  60723. }
  60724. // line system creation
  60725. var useVertexColor = (colors) ? true : false;
  60726. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60727. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60728. vertexData.applyToMesh(lineSystem, options.updatable);
  60729. return lineSystem;
  60730. };
  60731. /**
  60732. * Creates a line mesh
  60733. * 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
  60734. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60735. * * The parameter `points` is an array successive Vector3
  60736. * * 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
  60737. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60738. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60739. * * When updating an instance, remember that only point positions can change, not the number of points
  60740. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60741. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60742. * @param name defines the name of the new line system
  60743. * @param options defines the options used to create the line system
  60744. * @param scene defines the hosting scene
  60745. * @returns a new line mesh
  60746. */
  60747. MeshBuilder.CreateLines = function (name, options, scene) {
  60748. if (scene === void 0) { scene = null; }
  60749. var colors = (options.colors) ? [options.colors] : null;
  60750. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60751. return lines;
  60752. };
  60753. /**
  60754. * Creates a dashed line mesh
  60755. * * 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
  60756. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60757. * * The parameter `points` is an array successive Vector3
  60758. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60759. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60760. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60761. * * 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
  60762. * * When updating an instance, remember that only point positions can change, not the number of points
  60763. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60764. * @param name defines the name of the mesh
  60765. * @param options defines the options used to create the mesh
  60766. * @param scene defines the hosting scene
  60767. * @returns the dashed line mesh
  60768. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60769. */
  60770. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60771. if (scene === void 0) { scene = null; }
  60772. var points = options.points;
  60773. var instance = options.instance;
  60774. var gapSize = options.gapSize || 1;
  60775. var dashSize = options.dashSize || 3;
  60776. if (instance) { // dashed lines update
  60777. var positionFunction = function (positions) {
  60778. var curvect = BABYLON.Vector3.Zero();
  60779. var nbSeg = positions.length / 6;
  60780. var lg = 0;
  60781. var nb = 0;
  60782. var shft = 0;
  60783. var dashshft = 0;
  60784. var curshft = 0;
  60785. var p = 0;
  60786. var i = 0;
  60787. var j = 0;
  60788. for (i = 0; i < points.length - 1; i++) {
  60789. points[i + 1].subtractToRef(points[i], curvect);
  60790. lg += curvect.length();
  60791. }
  60792. shft = lg / nbSeg;
  60793. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60794. for (i = 0; i < points.length - 1; i++) {
  60795. points[i + 1].subtractToRef(points[i], curvect);
  60796. nb = Math.floor(curvect.length() / shft);
  60797. curvect.normalize();
  60798. j = 0;
  60799. while (j < nb && p < positions.length) {
  60800. curshft = shft * j;
  60801. positions[p] = points[i].x + curshft * curvect.x;
  60802. positions[p + 1] = points[i].y + curshft * curvect.y;
  60803. positions[p + 2] = points[i].z + curshft * curvect.z;
  60804. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60805. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60806. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60807. p += 6;
  60808. j++;
  60809. }
  60810. }
  60811. while (p < positions.length) {
  60812. positions[p] = points[i].x;
  60813. positions[p + 1] = points[i].y;
  60814. positions[p + 2] = points[i].z;
  60815. p += 3;
  60816. }
  60817. };
  60818. instance.updateMeshPositions(positionFunction, false);
  60819. return instance;
  60820. }
  60821. // dashed lines creation
  60822. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60823. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60824. vertexData.applyToMesh(dashedLines, options.updatable);
  60825. dashedLines.dashSize = dashSize;
  60826. dashedLines.gapSize = gapSize;
  60827. return dashedLines;
  60828. };
  60829. /**
  60830. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60831. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  60832. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60833. * * 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.
  60834. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60835. * * 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
  60836. * * 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
  60837. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60838. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60839. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60840. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60841. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60842. * @param name defines the name of the mesh
  60843. * @param options defines the options used to create the mesh
  60844. * @param scene defines the hosting scene
  60845. * @returns the extruded shape mesh
  60846. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60847. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60848. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60849. */
  60850. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60851. if (scene === void 0) { scene = null; }
  60852. var path = options.path;
  60853. var shape = options.shape;
  60854. var scale = options.scale || 1;
  60855. var rotation = options.rotation || 0;
  60856. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60857. var updatable = options.updatable;
  60858. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60859. var instance = options.instance || null;
  60860. var invertUV = options.invertUV || false;
  60861. 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);
  60862. };
  60863. /**
  60864. * Creates an custom extruded shape mesh.
  60865. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60866. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  60867. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60868. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  60869. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60870. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  60871. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60872. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60873. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60874. * * 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
  60875. * * 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
  60876. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60877. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60878. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60879. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60880. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60881. * @param name defines the name of the mesh
  60882. * @param options defines the options used to create the mesh
  60883. * @param scene defines the hosting scene
  60884. * @returns the custom extruded shape mesh
  60885. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60886. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60887. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60888. */
  60889. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60890. var path = options.path;
  60891. var shape = options.shape;
  60892. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60893. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60894. var ribbonCloseArray = options.ribbonCloseArray || false;
  60895. var ribbonClosePath = options.ribbonClosePath || false;
  60896. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60897. var updatable = options.updatable;
  60898. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60899. var instance = options.instance;
  60900. var invertUV = options.invertUV || false;
  60901. 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);
  60902. };
  60903. /**
  60904. * Creates lathe mesh.
  60905. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60906. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  60907. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60908. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60909. * * 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
  60910. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60911. * * 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
  60912. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60913. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60914. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60915. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60916. * @param name defines the name of the mesh
  60917. * @param options defines the options used to create the mesh
  60918. * @param scene defines the hosting scene
  60919. * @returns the lathe mesh
  60920. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60921. */
  60922. MeshBuilder.CreateLathe = function (name, options, scene) {
  60923. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60924. var closed = (options.closed === undefined) ? true : options.closed;
  60925. var shape = options.shape;
  60926. var radius = options.radius || 1;
  60927. var tessellation = options.tessellation || 64;
  60928. var updatable = options.updatable;
  60929. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60930. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60931. var pi2 = Math.PI * 2;
  60932. var paths = new Array();
  60933. var invertUV = options.invertUV || false;
  60934. var i = 0;
  60935. var p = 0;
  60936. var step = pi2 / tessellation * arc;
  60937. var rotated;
  60938. var path = new Array();
  60939. for (i = 0; i <= tessellation; i++) {
  60940. var path = [];
  60941. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60942. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60943. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60944. }
  60945. for (p = 0; p < shape.length; p++) {
  60946. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60947. path.push(rotated);
  60948. }
  60949. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60950. 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));
  60951. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60952. }
  60953. paths.push(path);
  60954. }
  60955. // lathe ribbon
  60956. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60957. return lathe;
  60958. };
  60959. /**
  60960. * Creates a plane mesh
  60961. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60962. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60963. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60964. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60965. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60966. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60967. * @param name defines the name of the mesh
  60968. * @param options defines the options used to create the mesh
  60969. * @param scene defines the hosting scene
  60970. * @returns the plane mesh
  60971. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60972. */
  60973. MeshBuilder.CreatePlane = function (name, options, scene) {
  60974. var plane = new BABYLON.Mesh(name, scene);
  60975. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60976. plane._originalBuilderSideOrientation = options.sideOrientation;
  60977. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60978. vertexData.applyToMesh(plane, options.updatable);
  60979. if (options.sourcePlane) {
  60980. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60981. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60982. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60983. plane.rotate(vectorProduct, product);
  60984. }
  60985. return plane;
  60986. };
  60987. /**
  60988. * Creates a ground mesh
  60989. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60990. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60991. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60992. * @param name defines the name of the mesh
  60993. * @param options defines the options used to create the mesh
  60994. * @param scene defines the hosting scene
  60995. * @returns the ground mesh
  60996. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60997. */
  60998. MeshBuilder.CreateGround = function (name, options, scene) {
  60999. var ground = new BABYLON.GroundMesh(name, scene);
  61000. ground._setReady(false);
  61001. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61002. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61003. ground._width = options.width || 1;
  61004. ground._height = options.height || 1;
  61005. ground._maxX = ground._width / 2;
  61006. ground._maxZ = ground._height / 2;
  61007. ground._minX = -ground._maxX;
  61008. ground._minZ = -ground._maxZ;
  61009. var vertexData = BABYLON.VertexData.CreateGround(options);
  61010. vertexData.applyToMesh(ground, options.updatable);
  61011. ground._setReady(true);
  61012. return ground;
  61013. };
  61014. /**
  61015. * Creates a tiled ground mesh
  61016. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61017. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61018. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  61019. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  61020. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61021. * @param name defines the name of the mesh
  61022. * @param options defines the options used to create the mesh
  61023. * @param scene defines the hosting scene
  61024. * @returns the tiled ground mesh
  61025. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61026. */
  61027. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61028. var tiledGround = new BABYLON.Mesh(name, scene);
  61029. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61030. vertexData.applyToMesh(tiledGround, options.updatable);
  61031. return tiledGround;
  61032. };
  61033. /**
  61034. * Creates a ground mesh from a height map
  61035. * * The parameter `url` sets the URL of the height map image resource.
  61036. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61037. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61038. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61039. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61040. * * 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.
  61041. * * 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).
  61042. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61043. * @param name defines the name of the mesh
  61044. * @param url defines the url to the height map
  61045. * @param options defines the options used to create the mesh
  61046. * @param scene defines the hosting scene
  61047. * @returns the ground mesh
  61048. * @see http://doc.babylonjs.com/babylon101/height_map
  61049. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61050. */
  61051. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61052. var width = options.width || 10.0;
  61053. var height = options.height || 10.0;
  61054. var subdivisions = options.subdivisions || 1 | 0;
  61055. var minHeight = options.minHeight || 0.0;
  61056. var maxHeight = options.maxHeight || 1.0;
  61057. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61058. var updatable = options.updatable;
  61059. var onReady = options.onReady;
  61060. var ground = new BABYLON.GroundMesh(name, scene);
  61061. ground._subdivisionsX = subdivisions;
  61062. ground._subdivisionsY = subdivisions;
  61063. ground._width = width;
  61064. ground._height = height;
  61065. ground._maxX = ground._width / 2.0;
  61066. ground._maxZ = ground._height / 2.0;
  61067. ground._minX = -ground._maxX;
  61068. ground._minZ = -ground._maxZ;
  61069. ground._setReady(false);
  61070. var onload = function (img) {
  61071. // Getting height map data
  61072. var canvas = document.createElement("canvas");
  61073. var context = canvas.getContext("2d");
  61074. if (!context) {
  61075. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61076. }
  61077. if (scene.isDisposed) {
  61078. return;
  61079. }
  61080. var bufferWidth = img.width;
  61081. var bufferHeight = img.height;
  61082. canvas.width = bufferWidth;
  61083. canvas.height = bufferHeight;
  61084. context.drawImage(img, 0, 0);
  61085. // Create VertexData from map data
  61086. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61087. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61088. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61089. width: width, height: height,
  61090. subdivisions: subdivisions,
  61091. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61092. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61093. });
  61094. vertexData.applyToMesh(ground, updatable);
  61095. //execute ready callback, if set
  61096. if (onReady) {
  61097. onReady(ground);
  61098. }
  61099. ground._setReady(true);
  61100. };
  61101. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61102. return ground;
  61103. };
  61104. /**
  61105. * Creates a polygon mesh
  61106. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61107. * * 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
  61108. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61109. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61110. * * 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)
  61111. * * Remember you can only change the shape positions, not their number when updating a polygon
  61112. * @param name defines the name of the mesh
  61113. * @param options defines the options used to create the mesh
  61114. * @param scene defines the hosting scene
  61115. * @returns the polygon mesh
  61116. */
  61117. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61118. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61119. var shape = options.shape;
  61120. var holes = options.holes || [];
  61121. var depth = options.depth || 0;
  61122. var contours = [];
  61123. var hole = [];
  61124. for (var i = 0; i < shape.length; i++) {
  61125. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61126. }
  61127. var epsilon = 0.00000001;
  61128. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61129. contours.pop();
  61130. }
  61131. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61132. for (var hNb = 0; hNb < holes.length; hNb++) {
  61133. hole = [];
  61134. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61135. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61136. }
  61137. polygonTriangulation.addHole(hole);
  61138. }
  61139. var polygon = polygonTriangulation.build(options.updatable, depth);
  61140. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61141. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61142. vertexData.applyToMesh(polygon, options.updatable);
  61143. return polygon;
  61144. };
  61145. ;
  61146. /**
  61147. * Creates an extruded polygon mesh, with depth in the Y direction.
  61148. * * 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)
  61149. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61150. * @param name defines the name of the mesh
  61151. * @param options defines the options used to create the mesh
  61152. * @param scene defines the hosting scene
  61153. * @returns the polygon mesh
  61154. */
  61155. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61156. return MeshBuilder.CreatePolygon(name, options, scene);
  61157. };
  61158. ;
  61159. /**
  61160. * Creates a tube mesh.
  61161. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61162. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61163. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61164. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61165. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61166. * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
  61167. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61168. * * 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
  61169. * * 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
  61170. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61171. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61172. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61173. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61174. * @param name defines the name of the mesh
  61175. * @param options defines the options used to create the mesh
  61176. * @param scene defines the hosting scene
  61177. * @returns the tube mesh
  61178. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61179. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61180. */
  61181. MeshBuilder.CreateTube = function (name, options, scene) {
  61182. var path = options.path;
  61183. var instance = options.instance;
  61184. var radius = 1.0;
  61185. if (instance) {
  61186. radius = instance.radius;
  61187. }
  61188. if (options.radius !== undefined) {
  61189. radius = options.radius;
  61190. }
  61191. ;
  61192. var tessellation = options.tessellation || 64 | 0;
  61193. var radiusFunction = options.radiusFunction || null;
  61194. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61195. var invertUV = options.invertUV || false;
  61196. var updatable = options.updatable;
  61197. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61198. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61199. // tube geometry
  61200. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61201. var tangents = path3D.getTangents();
  61202. var normals = path3D.getNormals();
  61203. var distances = path3D.getDistances();
  61204. var pi2 = Math.PI * 2;
  61205. var step = pi2 / tessellation * arc;
  61206. var returnRadius = function () { return radius; };
  61207. var radiusFunctionFinal = radiusFunction || returnRadius;
  61208. var circlePath;
  61209. var rad;
  61210. var normal;
  61211. var rotated;
  61212. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61213. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61214. for (var i = 0; i < path.length; i++) {
  61215. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61216. circlePath = Array(); // current circle array
  61217. normal = normals[i]; // current normal
  61218. for (var t = 0; t < tessellation; t++) {
  61219. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61220. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61221. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61222. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61223. circlePath[t] = rotated;
  61224. }
  61225. circlePaths[index] = circlePath;
  61226. index++;
  61227. }
  61228. // cap
  61229. var capPath = function (nbPoints, pathIndex) {
  61230. var pointCap = Array();
  61231. for (var i = 0; i < nbPoints; i++) {
  61232. pointCap.push(path[pathIndex]);
  61233. }
  61234. return pointCap;
  61235. };
  61236. switch (cap) {
  61237. case BABYLON.Mesh.NO_CAP:
  61238. break;
  61239. case BABYLON.Mesh.CAP_START:
  61240. circlePaths[0] = capPath(tessellation, 0);
  61241. circlePaths[1] = circlePaths[2].slice(0);
  61242. break;
  61243. case BABYLON.Mesh.CAP_END:
  61244. circlePaths[index] = circlePaths[index - 1].slice(0);
  61245. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61246. break;
  61247. case BABYLON.Mesh.CAP_ALL:
  61248. circlePaths[0] = capPath(tessellation, 0);
  61249. circlePaths[1] = circlePaths[2].slice(0);
  61250. circlePaths[index] = circlePaths[index - 1].slice(0);
  61251. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61252. break;
  61253. default:
  61254. break;
  61255. }
  61256. return circlePaths;
  61257. };
  61258. var path3D;
  61259. var pathArray;
  61260. if (instance) { // tube update
  61261. var arc = options.arc || instance.arc;
  61262. path3D = (instance.path3D).update(path);
  61263. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61264. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61265. instance.path3D = path3D;
  61266. instance.pathArray = pathArray;
  61267. instance.arc = arc;
  61268. instance.radius = radius;
  61269. return instance;
  61270. }
  61271. // tube creation
  61272. path3D = new BABYLON.Path3D(path);
  61273. var newPathArray = new Array();
  61274. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61275. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61276. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61277. tube.pathArray = pathArray;
  61278. tube.path3D = path3D;
  61279. tube.tessellation = tessellation;
  61280. tube.cap = cap;
  61281. tube.arc = options.arc;
  61282. tube.radius = radius;
  61283. return tube;
  61284. };
  61285. /**
  61286. * Creates a polyhedron mesh
  61287. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  61288. * * The parameter `size` (positive float, default 1) sets the polygon size
  61289. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61290. * * 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`
  61291. * * 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
  61292. * * 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)`)
  61293. * * 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
  61294. * * 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
  61295. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61296. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61297. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61298. * @param name defines the name of the mesh
  61299. * @param options defines the options used to create the mesh
  61300. * @param scene defines the hosting scene
  61301. * @returns the polyhedron mesh
  61302. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61303. */
  61304. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61305. var polyhedron = new BABYLON.Mesh(name, scene);
  61306. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61307. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61308. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61309. vertexData.applyToMesh(polyhedron, options.updatable);
  61310. return polyhedron;
  61311. };
  61312. /**
  61313. * Creates a decal mesh.
  61314. * 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
  61315. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61316. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61317. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61318. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61319. * @param name defines the name of the mesh
  61320. * @param sourceMesh defines the mesh where the decal must be applied
  61321. * @param options defines the options used to create the mesh
  61322. * @param scene defines the hosting scene
  61323. * @returns the decal mesh
  61324. * @see http://doc.babylonjs.com/how_to/decals
  61325. */
  61326. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61327. var indices = sourceMesh.getIndices();
  61328. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61329. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61330. var position = options.position || BABYLON.Vector3.Zero();
  61331. var normal = options.normal || BABYLON.Vector3.Up();
  61332. var size = options.size || BABYLON.Vector3.One();
  61333. var angle = options.angle || 0;
  61334. // Getting correct rotation
  61335. if (!normal) {
  61336. var target = new BABYLON.Vector3(0, 0, 1);
  61337. var camera = sourceMesh.getScene().activeCamera;
  61338. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61339. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61340. }
  61341. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61342. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61343. var pitch = Math.atan2(normal.y, len);
  61344. // Matrix
  61345. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61346. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61347. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61348. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61349. var vertexData = new BABYLON.VertexData();
  61350. vertexData.indices = [];
  61351. vertexData.positions = [];
  61352. vertexData.normals = [];
  61353. vertexData.uvs = [];
  61354. var currentVertexDataIndex = 0;
  61355. var extractDecalVector3 = function (indexId) {
  61356. var result = new BABYLON.PositionNormalVertex();
  61357. if (!indices || !positions || !normals) {
  61358. return result;
  61359. }
  61360. var vertexId = indices[indexId];
  61361. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61362. // Send vector to decal local world
  61363. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61364. // Get normal
  61365. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61366. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61367. return result;
  61368. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61369. var clip = function (vertices, axis) {
  61370. if (vertices.length === 0) {
  61371. return vertices;
  61372. }
  61373. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61374. var clipVertices = function (v0, v1) {
  61375. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61376. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61377. };
  61378. var result = new Array();
  61379. for (var index = 0; index < vertices.length; index += 3) {
  61380. var v1Out;
  61381. var v2Out;
  61382. var v3Out;
  61383. var total = 0;
  61384. var nV1 = null;
  61385. var nV2 = null;
  61386. var nV3 = null;
  61387. var nV4 = null;
  61388. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61389. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61390. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61391. v1Out = d1 > 0;
  61392. v2Out = d2 > 0;
  61393. v3Out = d3 > 0;
  61394. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61395. switch (total) {
  61396. case 0:
  61397. result.push(vertices[index]);
  61398. result.push(vertices[index + 1]);
  61399. result.push(vertices[index + 2]);
  61400. break;
  61401. case 1:
  61402. if (v1Out) {
  61403. nV1 = vertices[index + 1];
  61404. nV2 = vertices[index + 2];
  61405. nV3 = clipVertices(vertices[index], nV1);
  61406. nV4 = clipVertices(vertices[index], nV2);
  61407. }
  61408. if (v2Out) {
  61409. nV1 = vertices[index];
  61410. nV2 = vertices[index + 2];
  61411. nV3 = clipVertices(vertices[index + 1], nV1);
  61412. nV4 = clipVertices(vertices[index + 1], nV2);
  61413. result.push(nV3);
  61414. result.push(nV2.clone());
  61415. result.push(nV1.clone());
  61416. result.push(nV2.clone());
  61417. result.push(nV3.clone());
  61418. result.push(nV4);
  61419. break;
  61420. }
  61421. if (v3Out) {
  61422. nV1 = vertices[index];
  61423. nV2 = vertices[index + 1];
  61424. nV3 = clipVertices(vertices[index + 2], nV1);
  61425. nV4 = clipVertices(vertices[index + 2], nV2);
  61426. }
  61427. if (nV1 && nV2 && nV3 && nV4) {
  61428. result.push(nV1.clone());
  61429. result.push(nV2.clone());
  61430. result.push(nV3);
  61431. result.push(nV4);
  61432. result.push(nV3.clone());
  61433. result.push(nV2.clone());
  61434. }
  61435. break;
  61436. case 2:
  61437. if (!v1Out) {
  61438. nV1 = vertices[index].clone();
  61439. nV2 = clipVertices(nV1, vertices[index + 1]);
  61440. nV3 = clipVertices(nV1, vertices[index + 2]);
  61441. result.push(nV1);
  61442. result.push(nV2);
  61443. result.push(nV3);
  61444. }
  61445. if (!v2Out) {
  61446. nV1 = vertices[index + 1].clone();
  61447. nV2 = clipVertices(nV1, vertices[index + 2]);
  61448. nV3 = clipVertices(nV1, vertices[index]);
  61449. result.push(nV1);
  61450. result.push(nV2);
  61451. result.push(nV3);
  61452. }
  61453. if (!v3Out) {
  61454. nV1 = vertices[index + 2].clone();
  61455. nV2 = clipVertices(nV1, vertices[index]);
  61456. nV3 = clipVertices(nV1, vertices[index + 1]);
  61457. result.push(nV1);
  61458. result.push(nV2);
  61459. result.push(nV3);
  61460. }
  61461. break;
  61462. case 3:
  61463. break;
  61464. }
  61465. }
  61466. return result;
  61467. };
  61468. for (var index = 0; index < indices.length; index += 3) {
  61469. var faceVertices = new Array();
  61470. faceVertices.push(extractDecalVector3(index));
  61471. faceVertices.push(extractDecalVector3(index + 1));
  61472. faceVertices.push(extractDecalVector3(index + 2));
  61473. // Clip
  61474. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61475. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61476. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61477. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61478. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61479. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61480. if (faceVertices.length === 0) {
  61481. continue;
  61482. }
  61483. // Add UVs and get back to world
  61484. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61485. var vertex = faceVertices[vIndex];
  61486. //TODO check for Int32Array | Uint32Array | Uint16Array
  61487. vertexData.indices.push(currentVertexDataIndex);
  61488. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61489. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61490. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61491. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61492. currentVertexDataIndex++;
  61493. }
  61494. }
  61495. // Return mesh
  61496. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61497. vertexData.applyToMesh(decal);
  61498. decal.position = position.clone();
  61499. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61500. return decal;
  61501. };
  61502. // Privates
  61503. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61504. // extrusion geometry
  61505. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61506. var tangents = path3D.getTangents();
  61507. var normals = path3D.getNormals();
  61508. var binormals = path3D.getBinormals();
  61509. var distances = path3D.getDistances();
  61510. var angle = 0;
  61511. var returnScale = function () { return scale !== null ? scale : 1; };
  61512. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61513. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61514. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61515. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61516. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61517. for (var i = 0; i < curve.length; i++) {
  61518. var shapePath = new Array();
  61519. var angleStep = rotate(i, distances[i]);
  61520. var scaleRatio = scl(i, distances[i]);
  61521. for (var p = 0; p < shape.length; p++) {
  61522. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61523. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61524. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61525. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61526. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61527. shapePath[p] = rotated;
  61528. }
  61529. shapePaths[index] = shapePath;
  61530. angle += angleStep;
  61531. index++;
  61532. }
  61533. // cap
  61534. var capPath = function (shapePath) {
  61535. var pointCap = Array();
  61536. var barycenter = BABYLON.Vector3.Zero();
  61537. var i;
  61538. for (i = 0; i < shapePath.length; i++) {
  61539. barycenter.addInPlace(shapePath[i]);
  61540. }
  61541. barycenter.scaleInPlace(1.0 / shapePath.length);
  61542. for (i = 0; i < shapePath.length; i++) {
  61543. pointCap.push(barycenter);
  61544. }
  61545. return pointCap;
  61546. };
  61547. switch (cap) {
  61548. case BABYLON.Mesh.NO_CAP:
  61549. break;
  61550. case BABYLON.Mesh.CAP_START:
  61551. shapePaths[0] = capPath(shapePaths[2]);
  61552. shapePaths[1] = shapePaths[2];
  61553. break;
  61554. case BABYLON.Mesh.CAP_END:
  61555. shapePaths[index] = shapePaths[index - 1];
  61556. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61557. break;
  61558. case BABYLON.Mesh.CAP_ALL:
  61559. shapePaths[0] = capPath(shapePaths[2]);
  61560. shapePaths[1] = shapePaths[2];
  61561. shapePaths[index] = shapePaths[index - 1];
  61562. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61563. break;
  61564. default:
  61565. break;
  61566. }
  61567. return shapePaths;
  61568. };
  61569. var path3D;
  61570. var pathArray;
  61571. if (instance) { // instance update
  61572. path3D = (instance.path3D).update(curve);
  61573. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61574. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61575. return instance;
  61576. }
  61577. // extruded shape creation
  61578. path3D = new BABYLON.Path3D(curve);
  61579. var newShapePaths = new Array();
  61580. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61581. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61582. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61583. extrudedGeneric.pathArray = pathArray;
  61584. extrudedGeneric.path3D = path3D;
  61585. extrudedGeneric.cap = cap;
  61586. return extrudedGeneric;
  61587. };
  61588. return MeshBuilder;
  61589. }());
  61590. BABYLON.MeshBuilder = MeshBuilder;
  61591. })(BABYLON || (BABYLON = {}));
  61592. //# sourceMappingURL=babylon.meshBuilder.js.map
  61593. var BABYLON;
  61594. (function (BABYLON) {
  61595. /**
  61596. * Draco compression (https://google.github.io/draco/)
  61597. */
  61598. var DracoCompression = /** @class */ (function () {
  61599. /**
  61600. * Constructor
  61601. */
  61602. function DracoCompression() {
  61603. }
  61604. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61605. /**
  61606. * Returns true if the decoder is available.
  61607. */
  61608. get: function () {
  61609. if (typeof DracoDecoderModule !== "undefined") {
  61610. return true;
  61611. }
  61612. var decoder = DracoCompression.Configuration.decoder;
  61613. if (decoder) {
  61614. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61615. return true;
  61616. }
  61617. if (decoder.fallbackUrl) {
  61618. return true;
  61619. }
  61620. }
  61621. return false;
  61622. },
  61623. enumerable: true,
  61624. configurable: true
  61625. });
  61626. /**
  61627. * Stop all async operations and release resources.
  61628. */
  61629. DracoCompression.prototype.dispose = function () {
  61630. };
  61631. /**
  61632. * Decode Draco compressed mesh data to vertex data.
  61633. * @param data The array buffer view for the Draco compression data
  61634. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61635. * @returns A promise that resolves with the decoded vertex data
  61636. */
  61637. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61638. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61639. var module = wrappedModule.module;
  61640. var vertexData = new BABYLON.VertexData();
  61641. var buffer = new module.DecoderBuffer();
  61642. buffer.Init(data, data.byteLength);
  61643. var decoder = new module.Decoder();
  61644. var geometry;
  61645. var status;
  61646. try {
  61647. var type = decoder.GetEncodedGeometryType(buffer);
  61648. switch (type) {
  61649. case module.TRIANGULAR_MESH:
  61650. geometry = new module.Mesh();
  61651. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61652. break;
  61653. case module.POINT_CLOUD:
  61654. geometry = new module.PointCloud();
  61655. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61656. break;
  61657. default:
  61658. throw new Error("Invalid geometry type " + type);
  61659. }
  61660. if (!status.ok() || !geometry.ptr) {
  61661. throw new Error(status.error_msg());
  61662. }
  61663. var numPoints = geometry.num_points();
  61664. if (type === module.TRIANGULAR_MESH) {
  61665. var numFaces = geometry.num_faces();
  61666. var faceIndices = new module.DracoInt32Array();
  61667. try {
  61668. var indices = new Uint32Array(numFaces * 3);
  61669. for (var i = 0; i < numFaces; i++) {
  61670. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61671. var offset = i * 3;
  61672. indices[offset + 0] = faceIndices.GetValue(0);
  61673. indices[offset + 1] = faceIndices.GetValue(1);
  61674. indices[offset + 2] = faceIndices.GetValue(2);
  61675. }
  61676. vertexData.indices = indices;
  61677. }
  61678. finally {
  61679. module.destroy(faceIndices);
  61680. }
  61681. }
  61682. for (var kind in attributes) {
  61683. var uniqueId = attributes[kind];
  61684. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61685. var dracoData = new module.DracoFloat32Array();
  61686. try {
  61687. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61688. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61689. for (var i = 0; i < babylonData.length; i++) {
  61690. babylonData[i] = dracoData.GetValue(i);
  61691. }
  61692. vertexData.set(babylonData, kind);
  61693. }
  61694. finally {
  61695. module.destroy(dracoData);
  61696. }
  61697. }
  61698. }
  61699. finally {
  61700. if (geometry) {
  61701. module.destroy(geometry);
  61702. }
  61703. module.destroy(decoder);
  61704. module.destroy(buffer);
  61705. }
  61706. return vertexData;
  61707. });
  61708. };
  61709. DracoCompression._GetDecoderModule = function () {
  61710. if (!DracoCompression._DecoderModulePromise) {
  61711. var promise = null;
  61712. var config_1 = {};
  61713. if (typeof DracoDecoderModule !== "undefined") {
  61714. promise = Promise.resolve();
  61715. }
  61716. else {
  61717. var decoder = DracoCompression.Configuration.decoder;
  61718. if (decoder) {
  61719. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61720. promise = Promise.all([
  61721. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61722. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61723. config_1.wasmBinary = data;
  61724. })
  61725. ]);
  61726. }
  61727. else if (decoder.fallbackUrl) {
  61728. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61729. }
  61730. }
  61731. }
  61732. if (!promise) {
  61733. throw new Error("Draco decoder module is not available");
  61734. }
  61735. DracoCompression._DecoderModulePromise = promise.then(function () {
  61736. return new Promise(function (resolve) {
  61737. config_1.onModuleLoaded = function (decoderModule) {
  61738. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61739. resolve({ module: decoderModule });
  61740. };
  61741. DracoDecoderModule(config_1);
  61742. });
  61743. });
  61744. }
  61745. return DracoCompression._DecoderModulePromise;
  61746. };
  61747. DracoCompression._LoadScriptAsync = function (url) {
  61748. return new Promise(function (resolve, reject) {
  61749. BABYLON.Tools.LoadScript(url, function () {
  61750. resolve();
  61751. }, function (message) {
  61752. reject(new Error(message));
  61753. });
  61754. });
  61755. };
  61756. DracoCompression._LoadFileAsync = function (url) {
  61757. return new Promise(function (resolve, reject) {
  61758. BABYLON.Tools.LoadFile(url, function (data) {
  61759. resolve(data);
  61760. }, undefined, undefined, true, function (request, exception) {
  61761. reject(exception);
  61762. });
  61763. });
  61764. };
  61765. /**
  61766. * The configuration.
  61767. */
  61768. DracoCompression.Configuration = {
  61769. decoder: {
  61770. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61771. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61772. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61773. }
  61774. };
  61775. return DracoCompression;
  61776. }());
  61777. BABYLON.DracoCompression = DracoCompression;
  61778. })(BABYLON || (BABYLON = {}));
  61779. //# sourceMappingURL=babylon.dracoCompression.js.map
  61780. var BABYLON;
  61781. (function (BABYLON) {
  61782. var AudioEngine = /** @class */ (function () {
  61783. function AudioEngine() {
  61784. this._audioContext = null;
  61785. this._audioContextInitialized = false;
  61786. this.canUseWebAudio = false;
  61787. this.WarnedWebAudioUnsupported = false;
  61788. this.unlocked = false;
  61789. this.isMP3supported = false;
  61790. this.isOGGsupported = false;
  61791. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61792. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61793. this.canUseWebAudio = true;
  61794. }
  61795. var audioElem = document.createElement('audio');
  61796. try {
  61797. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61798. this.isMP3supported = true;
  61799. }
  61800. }
  61801. catch (e) {
  61802. // protect error during capability check.
  61803. }
  61804. try {
  61805. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61806. this.isOGGsupported = true;
  61807. }
  61808. }
  61809. catch (e) {
  61810. // protect error during capability check.
  61811. }
  61812. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61813. this._unlockiOSaudio();
  61814. }
  61815. else {
  61816. this.unlocked = true;
  61817. }
  61818. }
  61819. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61820. get: function () {
  61821. if (!this._audioContextInitialized) {
  61822. this._initializeAudioContext();
  61823. }
  61824. return this._audioContext;
  61825. },
  61826. enumerable: true,
  61827. configurable: true
  61828. });
  61829. AudioEngine.prototype._unlockiOSaudio = function () {
  61830. var _this = this;
  61831. var unlockaudio = function () {
  61832. if (!_this.audioContext) {
  61833. return;
  61834. }
  61835. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61836. var source = _this.audioContext.createBufferSource();
  61837. source.buffer = buffer;
  61838. source.connect(_this.audioContext.destination);
  61839. source.start(0);
  61840. setTimeout(function () {
  61841. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61842. _this.unlocked = true;
  61843. window.removeEventListener('touchend', unlockaudio, false);
  61844. if (_this.onAudioUnlocked) {
  61845. _this.onAudioUnlocked();
  61846. }
  61847. }
  61848. }, 0);
  61849. };
  61850. window.addEventListener('touchend', unlockaudio, false);
  61851. };
  61852. AudioEngine.prototype._initializeAudioContext = function () {
  61853. try {
  61854. if (this.canUseWebAudio) {
  61855. this._audioContext = new AudioContext();
  61856. // create a global volume gain node
  61857. this.masterGain = this._audioContext.createGain();
  61858. this.masterGain.gain.value = 1;
  61859. this.masterGain.connect(this._audioContext.destination);
  61860. this._audioContextInitialized = true;
  61861. }
  61862. }
  61863. catch (e) {
  61864. this.canUseWebAudio = false;
  61865. BABYLON.Tools.Error("Web Audio: " + e.message);
  61866. }
  61867. };
  61868. AudioEngine.prototype.dispose = function () {
  61869. if (this.canUseWebAudio && this._audioContextInitialized) {
  61870. if (this._connectedAnalyser && this._audioContext) {
  61871. this._connectedAnalyser.stopDebugCanvas();
  61872. this._connectedAnalyser.dispose();
  61873. this.masterGain.disconnect();
  61874. this.masterGain.connect(this._audioContext.destination);
  61875. this._connectedAnalyser = null;
  61876. }
  61877. this.masterGain.gain.value = 1;
  61878. }
  61879. this.WarnedWebAudioUnsupported = false;
  61880. };
  61881. AudioEngine.prototype.getGlobalVolume = function () {
  61882. if (this.canUseWebAudio && this._audioContextInitialized) {
  61883. return this.masterGain.gain.value;
  61884. }
  61885. else {
  61886. return -1;
  61887. }
  61888. };
  61889. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61890. if (this.canUseWebAudio && this._audioContextInitialized) {
  61891. this.masterGain.gain.value = newVolume;
  61892. }
  61893. };
  61894. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61895. if (this._connectedAnalyser) {
  61896. this._connectedAnalyser.stopDebugCanvas();
  61897. }
  61898. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61899. this._connectedAnalyser = analyser;
  61900. this.masterGain.disconnect();
  61901. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61902. }
  61903. };
  61904. return AudioEngine;
  61905. }());
  61906. BABYLON.AudioEngine = AudioEngine;
  61907. })(BABYLON || (BABYLON = {}));
  61908. //# sourceMappingURL=babylon.audioEngine.js.map
  61909. var BABYLON;
  61910. (function (BABYLON) {
  61911. var Sound = /** @class */ (function () {
  61912. /**
  61913. * Create a sound and attach it to a scene
  61914. * @param name Name of your sound
  61915. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61916. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61917. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61918. */
  61919. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61920. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61921. var _this = this;
  61922. this.autoplay = false;
  61923. this.loop = false;
  61924. this.useCustomAttenuation = false;
  61925. this.spatialSound = false;
  61926. this.refDistance = 1;
  61927. this.rolloffFactor = 1;
  61928. this.maxDistance = 100;
  61929. this.distanceModel = "linear";
  61930. this._panningModel = "equalpower";
  61931. this._playbackRate = 1;
  61932. this._streaming = false;
  61933. this._startTime = 0;
  61934. this._startOffset = 0;
  61935. this._position = BABYLON.Vector3.Zero();
  61936. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61937. this._volume = 1;
  61938. this._isReadyToPlay = false;
  61939. this.isPlaying = false;
  61940. this.isPaused = false;
  61941. this._isDirectional = false;
  61942. // Used if you'd like to create a directional sound.
  61943. // If not set, the sound will be omnidirectional
  61944. this._coneInnerAngle = 360;
  61945. this._coneOuterAngle = 360;
  61946. this._coneOuterGain = 0;
  61947. this._isOutputConnected = false;
  61948. this._urlType = "Unknown";
  61949. this.name = name;
  61950. this._scene = scene;
  61951. this._readyToPlayCallback = readyToPlayCallback;
  61952. // Default custom attenuation function is a linear attenuation
  61953. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61954. if (currentDistance < maxDistance) {
  61955. return currentVolume * (1 - currentDistance / maxDistance);
  61956. }
  61957. else {
  61958. return 0;
  61959. }
  61960. };
  61961. if (options) {
  61962. this.autoplay = options.autoplay || false;
  61963. this.loop = options.loop || false;
  61964. // if volume === 0, we need another way to check this option
  61965. if (options.volume !== undefined) {
  61966. this._volume = options.volume;
  61967. }
  61968. this.spatialSound = options.spatialSound || false;
  61969. this.maxDistance = options.maxDistance || 100;
  61970. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61971. this.rolloffFactor = options.rolloffFactor || 1;
  61972. this.refDistance = options.refDistance || 1;
  61973. this.distanceModel = options.distanceModel || "linear";
  61974. this._playbackRate = options.playbackRate || 1;
  61975. this._streaming = options.streaming || false;
  61976. }
  61977. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61978. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61979. this._soundGain.gain.value = this._volume;
  61980. this._inputAudioNode = this._soundGain;
  61981. this._ouputAudioNode = this._soundGain;
  61982. if (this.spatialSound) {
  61983. this._createSpatialParameters();
  61984. }
  61985. this._scene.mainSoundTrack.AddSound(this);
  61986. var validParameter = true;
  61987. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61988. if (urlOrArrayBuffer) {
  61989. try {
  61990. if (typeof (urlOrArrayBuffer) === "string")
  61991. this._urlType = "String";
  61992. if (Array.isArray(urlOrArrayBuffer))
  61993. this._urlType = "Array";
  61994. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61995. this._urlType = "ArrayBuffer";
  61996. var urls = [];
  61997. var codecSupportedFound = false;
  61998. switch (this._urlType) {
  61999. case "ArrayBuffer":
  62000. if (urlOrArrayBuffer.byteLength > 0) {
  62001. codecSupportedFound = true;
  62002. this._soundLoaded(urlOrArrayBuffer);
  62003. }
  62004. break;
  62005. case "String":
  62006. urls.push(urlOrArrayBuffer);
  62007. case "Array":
  62008. if (urls.length === 0)
  62009. urls = urlOrArrayBuffer;
  62010. // If we found a supported format, we load it immediately and stop the loop
  62011. for (var i = 0; i < urls.length; i++) {
  62012. var url = urls[i];
  62013. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62014. codecSupportedFound = true;
  62015. }
  62016. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62017. codecSupportedFound = true;
  62018. }
  62019. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62020. codecSupportedFound = true;
  62021. }
  62022. if (url.indexOf("blob:") !== -1) {
  62023. codecSupportedFound = true;
  62024. }
  62025. if (codecSupportedFound) {
  62026. // Loading sound using XHR2
  62027. if (!this._streaming) {
  62028. this._scene._loadFile(url, function (data) {
  62029. _this._soundLoaded(data);
  62030. }, undefined, true, true, function (exception) {
  62031. if (exception) {
  62032. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62033. }
  62034. BABYLON.Tools.Error("Sound creation aborted.");
  62035. _this._scene.mainSoundTrack.RemoveSound(_this);
  62036. });
  62037. }
  62038. // Streaming sound using HTML5 Audio tag
  62039. else {
  62040. this._htmlAudioElement = new Audio(url);
  62041. this._htmlAudioElement.controls = false;
  62042. this._htmlAudioElement.loop = this.loop;
  62043. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62044. this._htmlAudioElement.preload = "auto";
  62045. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62046. _this._isReadyToPlay = true;
  62047. if (_this.autoplay) {
  62048. _this.play();
  62049. }
  62050. if (_this._readyToPlayCallback) {
  62051. _this._readyToPlayCallback();
  62052. }
  62053. });
  62054. document.body.appendChild(this._htmlAudioElement);
  62055. }
  62056. break;
  62057. }
  62058. }
  62059. break;
  62060. default:
  62061. validParameter = false;
  62062. break;
  62063. }
  62064. if (!validParameter) {
  62065. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62066. }
  62067. else {
  62068. if (!codecSupportedFound) {
  62069. this._isReadyToPlay = true;
  62070. // Simulating a ready to play event to avoid breaking code path
  62071. if (this._readyToPlayCallback) {
  62072. window.setTimeout(function () {
  62073. if (_this._readyToPlayCallback) {
  62074. _this._readyToPlayCallback();
  62075. }
  62076. }, 1000);
  62077. }
  62078. }
  62079. }
  62080. }
  62081. catch (ex) {
  62082. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62083. this._scene.mainSoundTrack.RemoveSound(this);
  62084. }
  62085. }
  62086. }
  62087. else {
  62088. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62089. this._scene.mainSoundTrack.AddSound(this);
  62090. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62091. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62092. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62093. }
  62094. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62095. if (this._readyToPlayCallback) {
  62096. window.setTimeout(function () {
  62097. if (_this._readyToPlayCallback) {
  62098. _this._readyToPlayCallback();
  62099. }
  62100. }, 1000);
  62101. }
  62102. }
  62103. }
  62104. Sound.prototype.dispose = function () {
  62105. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62106. if (this.isPlaying) {
  62107. this.stop();
  62108. }
  62109. this._isReadyToPlay = false;
  62110. if (this.soundTrackId === -1) {
  62111. this._scene.mainSoundTrack.RemoveSound(this);
  62112. }
  62113. else {
  62114. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62115. }
  62116. if (this._soundGain) {
  62117. this._soundGain.disconnect();
  62118. this._soundGain = null;
  62119. }
  62120. if (this._soundPanner) {
  62121. this._soundPanner.disconnect();
  62122. this._soundPanner = null;
  62123. }
  62124. if (this._soundSource) {
  62125. this._soundSource.disconnect();
  62126. this._soundSource = null;
  62127. }
  62128. this._audioBuffer = null;
  62129. if (this._htmlAudioElement) {
  62130. this._htmlAudioElement.pause();
  62131. this._htmlAudioElement.src = "";
  62132. document.body.removeChild(this._htmlAudioElement);
  62133. }
  62134. if (this._connectedMesh && this._registerFunc) {
  62135. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62136. this._connectedMesh = null;
  62137. }
  62138. }
  62139. };
  62140. Sound.prototype.isReady = function () {
  62141. return this._isReadyToPlay;
  62142. };
  62143. Sound.prototype._soundLoaded = function (audioData) {
  62144. var _this = this;
  62145. if (!BABYLON.Engine.audioEngine.audioContext) {
  62146. return;
  62147. }
  62148. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62149. _this._audioBuffer = buffer;
  62150. _this._isReadyToPlay = true;
  62151. if (_this.autoplay) {
  62152. _this.play();
  62153. }
  62154. if (_this._readyToPlayCallback) {
  62155. _this._readyToPlayCallback();
  62156. }
  62157. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62158. };
  62159. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62160. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62161. this._audioBuffer = audioBuffer;
  62162. this._isReadyToPlay = true;
  62163. }
  62164. };
  62165. Sound.prototype.updateOptions = function (options) {
  62166. if (options) {
  62167. this.loop = options.loop || this.loop;
  62168. this.maxDistance = options.maxDistance || this.maxDistance;
  62169. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62170. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62171. this.refDistance = options.refDistance || this.refDistance;
  62172. this.distanceModel = options.distanceModel || this.distanceModel;
  62173. this._playbackRate = options.playbackRate || this._playbackRate;
  62174. this._updateSpatialParameters();
  62175. if (this.isPlaying) {
  62176. if (this._streaming) {
  62177. this._htmlAudioElement.playbackRate = this._playbackRate;
  62178. }
  62179. else {
  62180. if (this._soundSource) {
  62181. this._soundSource.playbackRate.value = this._playbackRate;
  62182. }
  62183. }
  62184. }
  62185. }
  62186. };
  62187. Sound.prototype._createSpatialParameters = function () {
  62188. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62189. if (this._scene.headphone) {
  62190. this._panningModel = "HRTF";
  62191. }
  62192. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62193. this._updateSpatialParameters();
  62194. this._soundPanner.connect(this._ouputAudioNode);
  62195. this._inputAudioNode = this._soundPanner;
  62196. }
  62197. };
  62198. Sound.prototype._updateSpatialParameters = function () {
  62199. if (this.spatialSound && this._soundPanner) {
  62200. if (this.useCustomAttenuation) {
  62201. // Tricks to disable in a way embedded Web Audio attenuation
  62202. this._soundPanner.distanceModel = "linear";
  62203. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62204. this._soundPanner.refDistance = 1;
  62205. this._soundPanner.rolloffFactor = 1;
  62206. this._soundPanner.panningModel = this._panningModel;
  62207. }
  62208. else {
  62209. this._soundPanner.distanceModel = this.distanceModel;
  62210. this._soundPanner.maxDistance = this.maxDistance;
  62211. this._soundPanner.refDistance = this.refDistance;
  62212. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62213. this._soundPanner.panningModel = this._panningModel;
  62214. }
  62215. }
  62216. };
  62217. Sound.prototype.switchPanningModelToHRTF = function () {
  62218. this._panningModel = "HRTF";
  62219. this._switchPanningModel();
  62220. };
  62221. Sound.prototype.switchPanningModelToEqualPower = function () {
  62222. this._panningModel = "equalpower";
  62223. this._switchPanningModel();
  62224. };
  62225. Sound.prototype._switchPanningModel = function () {
  62226. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62227. this._soundPanner.panningModel = this._panningModel;
  62228. }
  62229. };
  62230. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62231. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62232. if (this._isOutputConnected) {
  62233. this._ouputAudioNode.disconnect();
  62234. }
  62235. this._ouputAudioNode.connect(soundTrackAudioNode);
  62236. this._isOutputConnected = true;
  62237. }
  62238. };
  62239. /**
  62240. * Transform this sound into a directional source
  62241. * @param coneInnerAngle Size of the inner cone in degree
  62242. * @param coneOuterAngle Size of the outer cone in degree
  62243. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62244. */
  62245. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62246. if (coneOuterAngle < coneInnerAngle) {
  62247. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62248. return;
  62249. }
  62250. this._coneInnerAngle = coneInnerAngle;
  62251. this._coneOuterAngle = coneOuterAngle;
  62252. this._coneOuterGain = coneOuterGain;
  62253. this._isDirectional = true;
  62254. if (this.isPlaying && this.loop) {
  62255. this.stop();
  62256. this.play();
  62257. }
  62258. };
  62259. Sound.prototype.setPosition = function (newPosition) {
  62260. this._position = newPosition;
  62261. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62262. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62263. }
  62264. };
  62265. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62266. this._localDirection = newLocalDirection;
  62267. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62268. this._updateDirection();
  62269. }
  62270. };
  62271. Sound.prototype._updateDirection = function () {
  62272. if (!this._connectedMesh || !this._soundPanner) {
  62273. return;
  62274. }
  62275. var mat = this._connectedMesh.getWorldMatrix();
  62276. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62277. direction.normalize();
  62278. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62279. };
  62280. Sound.prototype.updateDistanceFromListener = function () {
  62281. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62282. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62283. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62284. }
  62285. };
  62286. Sound.prototype.setAttenuationFunction = function (callback) {
  62287. this._customAttenuationFunction = callback;
  62288. };
  62289. /**
  62290. * Play the sound
  62291. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62292. * @param offset (optional) Start the sound setting it at a specific time
  62293. */
  62294. Sound.prototype.play = function (time, offset) {
  62295. var _this = this;
  62296. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62297. try {
  62298. if (this._startOffset < 0) {
  62299. time = -this._startOffset;
  62300. this._startOffset = 0;
  62301. }
  62302. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62303. if (!this._soundSource || !this._streamingSource) {
  62304. if (this.spatialSound && this._soundPanner) {
  62305. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62306. if (this._isDirectional) {
  62307. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62308. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62309. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62310. if (this._connectedMesh) {
  62311. this._updateDirection();
  62312. }
  62313. else {
  62314. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62315. }
  62316. }
  62317. }
  62318. }
  62319. if (this._streaming) {
  62320. if (!this._streamingSource) {
  62321. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62322. this._htmlAudioElement.onended = function () { _this._onended(); };
  62323. this._htmlAudioElement.playbackRate = this._playbackRate;
  62324. }
  62325. this._streamingSource.disconnect();
  62326. this._streamingSource.connect(this._inputAudioNode);
  62327. this._htmlAudioElement.play();
  62328. }
  62329. else {
  62330. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62331. this._soundSource.buffer = this._audioBuffer;
  62332. this._soundSource.connect(this._inputAudioNode);
  62333. this._soundSource.loop = this.loop;
  62334. this._soundSource.playbackRate.value = this._playbackRate;
  62335. this._soundSource.onended = function () { _this._onended(); };
  62336. if (this._soundSource.buffer) {
  62337. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62338. }
  62339. }
  62340. this._startTime = startTime;
  62341. this.isPlaying = true;
  62342. this.isPaused = false;
  62343. }
  62344. catch (ex) {
  62345. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62346. }
  62347. }
  62348. };
  62349. Sound.prototype._onended = function () {
  62350. this.isPlaying = false;
  62351. if (this.onended) {
  62352. this.onended();
  62353. }
  62354. };
  62355. /**
  62356. * Stop the sound
  62357. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62358. */
  62359. Sound.prototype.stop = function (time) {
  62360. if (this.isPlaying) {
  62361. if (this._streaming) {
  62362. this._htmlAudioElement.pause();
  62363. // Test needed for Firefox or it will generate an Invalid State Error
  62364. if (this._htmlAudioElement.currentTime > 0) {
  62365. this._htmlAudioElement.currentTime = 0;
  62366. }
  62367. }
  62368. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62369. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62370. this._soundSource.stop(stopTime);
  62371. this._soundSource.onended = function () { };
  62372. if (!this.isPaused) {
  62373. this._startOffset = 0;
  62374. }
  62375. }
  62376. this.isPlaying = false;
  62377. }
  62378. };
  62379. Sound.prototype.pause = function () {
  62380. if (this.isPlaying) {
  62381. this.isPaused = true;
  62382. if (this._streaming) {
  62383. this._htmlAudioElement.pause();
  62384. }
  62385. else if (BABYLON.Engine.audioEngine.audioContext) {
  62386. this.stop(0);
  62387. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62388. }
  62389. }
  62390. };
  62391. Sound.prototype.setVolume = function (newVolume, time) {
  62392. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62393. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62394. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62395. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62396. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62397. }
  62398. else {
  62399. this._soundGain.gain.value = newVolume;
  62400. }
  62401. }
  62402. this._volume = newVolume;
  62403. };
  62404. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62405. this._playbackRate = newPlaybackRate;
  62406. if (this.isPlaying) {
  62407. if (this._streaming) {
  62408. this._htmlAudioElement.playbackRate = this._playbackRate;
  62409. }
  62410. else if (this._soundSource) {
  62411. this._soundSource.playbackRate.value = this._playbackRate;
  62412. }
  62413. }
  62414. };
  62415. Sound.prototype.getVolume = function () {
  62416. return this._volume;
  62417. };
  62418. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62419. var _this = this;
  62420. if (this._connectedMesh && this._registerFunc) {
  62421. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62422. this._registerFunc = null;
  62423. }
  62424. this._connectedMesh = meshToConnectTo;
  62425. if (!this.spatialSound) {
  62426. this.spatialSound = true;
  62427. this._createSpatialParameters();
  62428. if (this.isPlaying && this.loop) {
  62429. this.stop();
  62430. this.play();
  62431. }
  62432. }
  62433. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62434. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62435. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62436. };
  62437. Sound.prototype.detachFromMesh = function () {
  62438. if (this._connectedMesh && this._registerFunc) {
  62439. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62440. this._registerFunc = null;
  62441. this._connectedMesh = null;
  62442. }
  62443. };
  62444. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62445. if (!node.getBoundingInfo) {
  62446. return;
  62447. }
  62448. var mesh = node;
  62449. var boundingInfo = mesh.getBoundingInfo();
  62450. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62451. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62452. this._updateDirection();
  62453. }
  62454. };
  62455. Sound.prototype.clone = function () {
  62456. var _this = this;
  62457. if (!this._streaming) {
  62458. var setBufferAndRun = function () {
  62459. if (_this._isReadyToPlay) {
  62460. clonedSound._audioBuffer = _this.getAudioBuffer();
  62461. clonedSound._isReadyToPlay = true;
  62462. if (clonedSound.autoplay) {
  62463. clonedSound.play();
  62464. }
  62465. }
  62466. else {
  62467. window.setTimeout(setBufferAndRun, 300);
  62468. }
  62469. };
  62470. var currentOptions = {
  62471. autoplay: this.autoplay, loop: this.loop,
  62472. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62473. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62474. refDistance: this.refDistance, distanceModel: this.distanceModel
  62475. };
  62476. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62477. if (this.useCustomAttenuation) {
  62478. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62479. }
  62480. clonedSound.setPosition(this._position);
  62481. clonedSound.setPlaybackRate(this._playbackRate);
  62482. setBufferAndRun();
  62483. return clonedSound;
  62484. }
  62485. // Can't clone a streaming sound
  62486. else {
  62487. return null;
  62488. }
  62489. };
  62490. Sound.prototype.getAudioBuffer = function () {
  62491. return this._audioBuffer;
  62492. };
  62493. Sound.prototype.serialize = function () {
  62494. var serializationObject = {
  62495. name: this.name,
  62496. url: this.name,
  62497. autoplay: this.autoplay,
  62498. loop: this.loop,
  62499. volume: this._volume,
  62500. spatialSound: this.spatialSound,
  62501. maxDistance: this.maxDistance,
  62502. rolloffFactor: this.rolloffFactor,
  62503. refDistance: this.refDistance,
  62504. distanceModel: this.distanceModel,
  62505. playbackRate: this._playbackRate,
  62506. panningModel: this._panningModel,
  62507. soundTrackId: this.soundTrackId
  62508. };
  62509. if (this.spatialSound) {
  62510. if (this._connectedMesh)
  62511. serializationObject.connectedMeshId = this._connectedMesh.id;
  62512. serializationObject.position = this._position.asArray();
  62513. serializationObject.refDistance = this.refDistance;
  62514. serializationObject.distanceModel = this.distanceModel;
  62515. serializationObject.isDirectional = this._isDirectional;
  62516. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62517. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62518. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62519. serializationObject.coneOuterGain = this._coneOuterGain;
  62520. }
  62521. return serializationObject;
  62522. };
  62523. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62524. var soundName = parsedSound.name;
  62525. var soundUrl;
  62526. if (parsedSound.url) {
  62527. soundUrl = rootUrl + parsedSound.url;
  62528. }
  62529. else {
  62530. soundUrl = rootUrl + soundName;
  62531. }
  62532. var options = {
  62533. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62534. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62535. rolloffFactor: parsedSound.rolloffFactor,
  62536. refDistance: parsedSound.refDistance,
  62537. distanceModel: parsedSound.distanceModel,
  62538. playbackRate: parsedSound.playbackRate
  62539. };
  62540. var newSound;
  62541. if (!sourceSound) {
  62542. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62543. scene._addPendingData(newSound);
  62544. }
  62545. else {
  62546. var setBufferAndRun = function () {
  62547. if (sourceSound._isReadyToPlay) {
  62548. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62549. newSound._isReadyToPlay = true;
  62550. if (newSound.autoplay) {
  62551. newSound.play();
  62552. }
  62553. }
  62554. else {
  62555. window.setTimeout(setBufferAndRun, 300);
  62556. }
  62557. };
  62558. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62559. setBufferAndRun();
  62560. }
  62561. if (parsedSound.position) {
  62562. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62563. newSound.setPosition(soundPosition);
  62564. }
  62565. if (parsedSound.isDirectional) {
  62566. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62567. if (parsedSound.localDirectionToMesh) {
  62568. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62569. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62570. }
  62571. }
  62572. if (parsedSound.connectedMeshId) {
  62573. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62574. if (connectedMesh) {
  62575. newSound.attachToMesh(connectedMesh);
  62576. }
  62577. }
  62578. return newSound;
  62579. };
  62580. return Sound;
  62581. }());
  62582. BABYLON.Sound = Sound;
  62583. })(BABYLON || (BABYLON = {}));
  62584. //# sourceMappingURL=babylon.sound.js.map
  62585. var BABYLON;
  62586. (function (BABYLON) {
  62587. var SoundTrack = /** @class */ (function () {
  62588. function SoundTrack(scene, options) {
  62589. this.id = -1;
  62590. this._isMainTrack = false;
  62591. this._isInitialized = false;
  62592. this._scene = scene;
  62593. this.soundCollection = new Array();
  62594. this._options = options;
  62595. if (!this._isMainTrack) {
  62596. this._scene.soundTracks.push(this);
  62597. this.id = this._scene.soundTracks.length - 1;
  62598. }
  62599. }
  62600. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62601. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62602. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62603. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62604. if (this._options) {
  62605. if (this._options.volume) {
  62606. this._outputAudioNode.gain.value = this._options.volume;
  62607. }
  62608. if (this._options.mainTrack) {
  62609. this._isMainTrack = this._options.mainTrack;
  62610. }
  62611. }
  62612. this._isInitialized = true;
  62613. }
  62614. };
  62615. SoundTrack.prototype.dispose = function () {
  62616. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62617. if (this._connectedAnalyser) {
  62618. this._connectedAnalyser.stopDebugCanvas();
  62619. }
  62620. while (this.soundCollection.length) {
  62621. this.soundCollection[0].dispose();
  62622. }
  62623. if (this._outputAudioNode) {
  62624. this._outputAudioNode.disconnect();
  62625. }
  62626. this._outputAudioNode = null;
  62627. }
  62628. };
  62629. SoundTrack.prototype.AddSound = function (sound) {
  62630. if (!this._isInitialized) {
  62631. this._initializeSoundTrackAudioGraph();
  62632. }
  62633. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62634. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62635. }
  62636. if (sound.soundTrackId) {
  62637. if (sound.soundTrackId === -1) {
  62638. this._scene.mainSoundTrack.RemoveSound(sound);
  62639. }
  62640. else {
  62641. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62642. }
  62643. }
  62644. this.soundCollection.push(sound);
  62645. sound.soundTrackId = this.id;
  62646. };
  62647. SoundTrack.prototype.RemoveSound = function (sound) {
  62648. var index = this.soundCollection.indexOf(sound);
  62649. if (index !== -1) {
  62650. this.soundCollection.splice(index, 1);
  62651. }
  62652. };
  62653. SoundTrack.prototype.setVolume = function (newVolume) {
  62654. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62655. this._outputAudioNode.gain.value = newVolume;
  62656. }
  62657. };
  62658. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62659. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62660. for (var i = 0; i < this.soundCollection.length; i++) {
  62661. this.soundCollection[i].switchPanningModelToHRTF();
  62662. }
  62663. }
  62664. };
  62665. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62666. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62667. for (var i = 0; i < this.soundCollection.length; i++) {
  62668. this.soundCollection[i].switchPanningModelToEqualPower();
  62669. }
  62670. }
  62671. };
  62672. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62673. if (this._connectedAnalyser) {
  62674. this._connectedAnalyser.stopDebugCanvas();
  62675. }
  62676. this._connectedAnalyser = analyser;
  62677. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62678. this._outputAudioNode.disconnect();
  62679. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62680. }
  62681. };
  62682. return SoundTrack;
  62683. }());
  62684. BABYLON.SoundTrack = SoundTrack;
  62685. })(BABYLON || (BABYLON = {}));
  62686. //# sourceMappingURL=babylon.soundtrack.js.map
  62687. var BABYLON;
  62688. (function (BABYLON) {
  62689. /**
  62690. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62691. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62692. */
  62693. var Analyser = /** @class */ (function () {
  62694. /**
  62695. * Creates a new analyser
  62696. * @param scene defines hosting scene
  62697. */
  62698. function Analyser(scene) {
  62699. /**
  62700. * Gets or sets the smoothing
  62701. * @ignorenaming
  62702. */
  62703. this.SMOOTHING = 0.75;
  62704. /**
  62705. * Gets or sets the FFT table size
  62706. * @ignorenaming
  62707. */
  62708. this.FFT_SIZE = 512;
  62709. /**
  62710. * Gets or sets the bar graph amplitude
  62711. * @ignorenaming
  62712. */
  62713. this.BARGRAPHAMPLITUDE = 256;
  62714. /**
  62715. * Gets or sets the position of the debug canvas
  62716. * @ignorenaming
  62717. */
  62718. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62719. /**
  62720. * Gets or sets the debug canvas size
  62721. * @ignorenaming
  62722. */
  62723. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62724. this._scene = scene;
  62725. this._audioEngine = BABYLON.Engine.audioEngine;
  62726. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62727. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62728. this._webAudioAnalyser.minDecibels = -140;
  62729. this._webAudioAnalyser.maxDecibels = 0;
  62730. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62731. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62732. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62733. }
  62734. }
  62735. /**
  62736. * Get the number of data values you will have to play with for the visualization
  62737. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62738. * @returns a number
  62739. */
  62740. Analyser.prototype.getFrequencyBinCount = function () {
  62741. if (this._audioEngine.canUseWebAudio) {
  62742. return this._webAudioAnalyser.frequencyBinCount;
  62743. }
  62744. else {
  62745. return 0;
  62746. }
  62747. };
  62748. /**
  62749. * Gets the current frequency data as a byte array
  62750. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62751. * @returns a Uint8Array
  62752. */
  62753. Analyser.prototype.getByteFrequencyData = function () {
  62754. if (this._audioEngine.canUseWebAudio) {
  62755. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62756. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62757. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62758. }
  62759. return this._byteFreqs;
  62760. };
  62761. /**
  62762. * Gets the current waveform as a byte array
  62763. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62764. * @returns a Uint8Array
  62765. */
  62766. Analyser.prototype.getByteTimeDomainData = function () {
  62767. if (this._audioEngine.canUseWebAudio) {
  62768. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62769. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62770. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62771. }
  62772. return this._byteTime;
  62773. };
  62774. /**
  62775. * Gets the current frequency data as a float array
  62776. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62777. * @returns a Float32Array
  62778. */
  62779. Analyser.prototype.getFloatFrequencyData = function () {
  62780. if (this._audioEngine.canUseWebAudio) {
  62781. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62782. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62783. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62784. }
  62785. return this._floatFreqs;
  62786. };
  62787. /**
  62788. * Renders the debug canvas
  62789. */
  62790. Analyser.prototype.drawDebugCanvas = function () {
  62791. var _this = this;
  62792. if (this._audioEngine.canUseWebAudio) {
  62793. if (!this._debugCanvas) {
  62794. this._debugCanvas = document.createElement("canvas");
  62795. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62796. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62797. this._debugCanvas.style.position = "absolute";
  62798. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62799. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62800. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62801. document.body.appendChild(this._debugCanvas);
  62802. this._registerFunc = function () {
  62803. _this.drawDebugCanvas();
  62804. };
  62805. this._scene.registerBeforeRender(this._registerFunc);
  62806. }
  62807. if (this._registerFunc && this._debugCanvasContext) {
  62808. var workingArray = this.getByteFrequencyData();
  62809. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62810. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62811. // Draw the frequency domain chart.
  62812. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62813. var value = workingArray[i];
  62814. var percent = value / this.BARGRAPHAMPLITUDE;
  62815. var height = this.DEBUGCANVASSIZE.height * percent;
  62816. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62817. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62818. var hue = i / this.getFrequencyBinCount() * 360;
  62819. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62820. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62821. }
  62822. }
  62823. }
  62824. };
  62825. /**
  62826. * Stops rendering the debug canvas and removes it
  62827. */
  62828. Analyser.prototype.stopDebugCanvas = function () {
  62829. if (this._debugCanvas) {
  62830. if (this._registerFunc) {
  62831. this._scene.unregisterBeforeRender(this._registerFunc);
  62832. this._registerFunc = null;
  62833. }
  62834. document.body.removeChild(this._debugCanvas);
  62835. this._debugCanvas = null;
  62836. this._debugCanvasContext = null;
  62837. }
  62838. };
  62839. /**
  62840. * Connects two audio nodes
  62841. * @param inputAudioNode defines first node to connect
  62842. * @param outputAudioNode defines second node to connect
  62843. */
  62844. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62845. if (this._audioEngine.canUseWebAudio) {
  62846. inputAudioNode.connect(this._webAudioAnalyser);
  62847. this._webAudioAnalyser.connect(outputAudioNode);
  62848. }
  62849. };
  62850. /**
  62851. * Releases all associated resources
  62852. */
  62853. Analyser.prototype.dispose = function () {
  62854. if (this._audioEngine.canUseWebAudio) {
  62855. this._webAudioAnalyser.disconnect();
  62856. }
  62857. };
  62858. return Analyser;
  62859. }());
  62860. BABYLON.Analyser = Analyser;
  62861. })(BABYLON || (BABYLON = {}));
  62862. //# sourceMappingURL=babylon.analyser.js.map
  62863. var BABYLON;
  62864. (function (BABYLON) {
  62865. var CubeTexture = /** @class */ (function (_super) {
  62866. __extends(CubeTexture, _super);
  62867. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62868. if (extensions === void 0) { extensions = null; }
  62869. if (noMipmap === void 0) { noMipmap = false; }
  62870. if (files === void 0) { files = null; }
  62871. if (onLoad === void 0) { onLoad = null; }
  62872. if (onError === void 0) { onError = null; }
  62873. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62874. if (prefiltered === void 0) { prefiltered = false; }
  62875. if (forcedExtension === void 0) { forcedExtension = null; }
  62876. var _this = _super.call(this, scene) || this;
  62877. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62878. /**
  62879. * Gets or sets the center of the bounding box associated with the cube texture
  62880. * It must define where the camera used to render the texture was set
  62881. */
  62882. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62883. _this._rotationY = 0;
  62884. _this.name = rootUrl;
  62885. _this.url = rootUrl;
  62886. _this._noMipmap = noMipmap;
  62887. _this.hasAlpha = false;
  62888. _this._format = format;
  62889. _this._prefiltered = prefiltered;
  62890. _this.isCube = true;
  62891. _this._textureMatrix = BABYLON.Matrix.Identity();
  62892. if (prefiltered) {
  62893. _this.gammaSpace = false;
  62894. }
  62895. if (!rootUrl && !files) {
  62896. return _this;
  62897. }
  62898. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62899. var lastDot = rootUrl.lastIndexOf(".");
  62900. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62901. var isDDS = (extension === ".dds");
  62902. if (!files) {
  62903. if (!isDDS && !extensions) {
  62904. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62905. }
  62906. files = [];
  62907. if (extensions) {
  62908. for (var index = 0; index < extensions.length; index++) {
  62909. files.push(rootUrl + extensions[index]);
  62910. }
  62911. }
  62912. }
  62913. _this._files = files;
  62914. if (!_this._texture) {
  62915. if (!scene.useDelayedTextureLoading) {
  62916. if (prefiltered) {
  62917. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62918. }
  62919. else {
  62920. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62921. }
  62922. }
  62923. else {
  62924. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62925. }
  62926. }
  62927. else if (onLoad) {
  62928. if (_this._texture.isReady) {
  62929. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62930. }
  62931. else {
  62932. _this._texture.onLoadedObservable.add(onLoad);
  62933. }
  62934. }
  62935. return _this;
  62936. }
  62937. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62938. get: function () {
  62939. return this._boundingBoxSize;
  62940. },
  62941. /**
  62942. * Gets or sets the size of the bounding box associated with the cube texture
  62943. * When defined, the cubemap will switch to local mode
  62944. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62945. * @example https://www.babylonjs-playground.com/#RNASML
  62946. */
  62947. set: function (value) {
  62948. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62949. return;
  62950. }
  62951. this._boundingBoxSize = value;
  62952. var scene = this.getScene();
  62953. if (scene) {
  62954. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62955. }
  62956. },
  62957. enumerable: true,
  62958. configurable: true
  62959. });
  62960. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62961. /**
  62962. * Gets texture matrix rotation angle around Y axis radians.
  62963. */
  62964. get: function () {
  62965. return this._rotationY;
  62966. },
  62967. /**
  62968. * Sets texture matrix rotation angle around Y axis in radians.
  62969. */
  62970. set: function (value) {
  62971. this._rotationY = value;
  62972. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62973. },
  62974. enumerable: true,
  62975. configurable: true
  62976. });
  62977. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62978. var rootUrlKey = "";
  62979. files.forEach(function (url) { return rootUrlKey += url; });
  62980. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62981. };
  62982. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  62983. if (forcedExtension === void 0) { forcedExtension = null; }
  62984. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  62985. };
  62986. // Methods
  62987. CubeTexture.prototype.delayLoad = function () {
  62988. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62989. return;
  62990. }
  62991. var scene = this.getScene();
  62992. if (!scene) {
  62993. return;
  62994. }
  62995. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62996. this._texture = this._getFromCache(this.url, this._noMipmap);
  62997. if (!this._texture) {
  62998. if (this._prefiltered) {
  62999. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63000. }
  63001. else {
  63002. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63003. }
  63004. }
  63005. };
  63006. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63007. return this._textureMatrix;
  63008. };
  63009. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63010. this._textureMatrix = value;
  63011. };
  63012. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63013. var texture = BABYLON.SerializationHelper.Parse(function () {
  63014. var prefiltered = false;
  63015. if (parsedTexture.prefiltered) {
  63016. prefiltered = parsedTexture.prefiltered;
  63017. }
  63018. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63019. }, parsedTexture, scene);
  63020. // Local Cubemaps
  63021. if (parsedTexture.boundingBoxPosition) {
  63022. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63023. }
  63024. if (parsedTexture.boundingBoxSize) {
  63025. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63026. }
  63027. // Animations
  63028. if (parsedTexture.animations) {
  63029. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63030. var parsedAnimation = parsedTexture.animations[animationIndex];
  63031. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63032. }
  63033. }
  63034. return texture;
  63035. };
  63036. CubeTexture.prototype.clone = function () {
  63037. var _this = this;
  63038. return BABYLON.SerializationHelper.Clone(function () {
  63039. var scene = _this.getScene();
  63040. if (!scene) {
  63041. return _this;
  63042. }
  63043. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63044. }, this);
  63045. };
  63046. __decorate([
  63047. BABYLON.serialize("rotationY")
  63048. ], CubeTexture.prototype, "_rotationY", void 0);
  63049. return CubeTexture;
  63050. }(BABYLON.BaseTexture));
  63051. BABYLON.CubeTexture = CubeTexture;
  63052. })(BABYLON || (BABYLON = {}));
  63053. //# sourceMappingURL=babylon.cubeTexture.js.map
  63054. var BABYLON;
  63055. (function (BABYLON) {
  63056. var RenderTargetTexture = /** @class */ (function (_super) {
  63057. __extends(RenderTargetTexture, _super);
  63058. /**
  63059. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63060. * or used a shadow, depth texture...
  63061. * @param name The friendly name of the texture
  63062. * @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)
  63063. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63064. * @param generateMipMaps True if mip maps need to be generated after render.
  63065. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63066. * @param type The type of the buffer in the RTT (int, half float, float...)
  63067. * @param isCube True if a cube texture needs to be created
  63068. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63069. * @param generateDepthBuffer True to generate a depth buffer
  63070. * @param generateStencilBuffer True to generate a stencil buffer
  63071. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63072. */
  63073. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63074. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63075. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63076. if (isCube === void 0) { isCube = false; }
  63077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63078. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63079. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63080. if (isMulti === void 0) { isMulti = false; }
  63081. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63082. _this.isCube = isCube;
  63083. /**
  63084. * Use this list to define the list of mesh you want to render.
  63085. */
  63086. _this.renderList = new Array();
  63087. _this.renderParticles = true;
  63088. _this.renderSprites = false;
  63089. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63090. _this.ignoreCameraViewport = false;
  63091. // Events
  63092. /**
  63093. * An event triggered when the texture is unbind.
  63094. */
  63095. _this.onBeforeBindObservable = new BABYLON.Observable();
  63096. /**
  63097. * An event triggered when the texture is unbind.
  63098. */
  63099. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63100. /**
  63101. * An event triggered before rendering the texture
  63102. */
  63103. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63104. /**
  63105. * An event triggered after rendering the texture
  63106. */
  63107. _this.onAfterRenderObservable = new BABYLON.Observable();
  63108. /**
  63109. * An event triggered after the texture clear
  63110. */
  63111. _this.onClearObservable = new BABYLON.Observable();
  63112. _this._currentRefreshId = -1;
  63113. _this._refreshRate = 1;
  63114. _this._samples = 1;
  63115. /**
  63116. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63117. * It must define where the camera used to render the texture is set
  63118. */
  63119. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63120. scene = _this.getScene();
  63121. if (!scene) {
  63122. return _this;
  63123. }
  63124. _this._engine = scene.getEngine();
  63125. _this.name = name;
  63126. _this.isRenderTarget = true;
  63127. _this._initialSizeParameter = size;
  63128. _this._processSizeParameter(size);
  63129. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63130. });
  63131. _this._generateMipMaps = generateMipMaps ? true : false;
  63132. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63133. // Rendering groups
  63134. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63135. if (isMulti) {
  63136. return _this;
  63137. }
  63138. _this._renderTargetOptions = {
  63139. generateMipMaps: generateMipMaps,
  63140. type: type,
  63141. samplingMode: samplingMode,
  63142. generateDepthBuffer: generateDepthBuffer,
  63143. generateStencilBuffer: generateStencilBuffer
  63144. };
  63145. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63146. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63147. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63148. }
  63149. if (isCube) {
  63150. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63151. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63152. _this._textureMatrix = BABYLON.Matrix.Identity();
  63153. }
  63154. else {
  63155. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63156. }
  63157. return _this;
  63158. }
  63159. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63160. get: function () {
  63161. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63162. },
  63163. enumerable: true,
  63164. configurable: true
  63165. });
  63166. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63167. get: function () {
  63168. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63169. },
  63170. enumerable: true,
  63171. configurable: true
  63172. });
  63173. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63174. get: function () {
  63175. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63176. },
  63177. enumerable: true,
  63178. configurable: true
  63179. });
  63180. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63181. set: function (callback) {
  63182. if (this._onAfterUnbindObserver) {
  63183. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63184. }
  63185. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63186. },
  63187. enumerable: true,
  63188. configurable: true
  63189. });
  63190. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63191. set: function (callback) {
  63192. if (this._onBeforeRenderObserver) {
  63193. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63194. }
  63195. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63196. },
  63197. enumerable: true,
  63198. configurable: true
  63199. });
  63200. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63201. set: function (callback) {
  63202. if (this._onAfterRenderObserver) {
  63203. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63204. }
  63205. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63206. },
  63207. enumerable: true,
  63208. configurable: true
  63209. });
  63210. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63211. set: function (callback) {
  63212. if (this._onClearObserver) {
  63213. this.onClearObservable.remove(this._onClearObserver);
  63214. }
  63215. this._onClearObserver = this.onClearObservable.add(callback);
  63216. },
  63217. enumerable: true,
  63218. configurable: true
  63219. });
  63220. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63221. get: function () {
  63222. return this._renderTargetOptions;
  63223. },
  63224. enumerable: true,
  63225. configurable: true
  63226. });
  63227. RenderTargetTexture.prototype._onRatioRescale = function () {
  63228. if (this._sizeRatio) {
  63229. this.resize(this._initialSizeParameter);
  63230. }
  63231. };
  63232. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63233. get: function () {
  63234. return this._boundingBoxSize;
  63235. },
  63236. /**
  63237. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63238. * When defined, the cubemap will switch to local mode
  63239. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63240. * @example https://www.babylonjs-playground.com/#RNASML
  63241. */
  63242. set: function (value) {
  63243. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63244. return;
  63245. }
  63246. this._boundingBoxSize = value;
  63247. var scene = this.getScene();
  63248. if (scene) {
  63249. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63250. }
  63251. },
  63252. enumerable: true,
  63253. configurable: true
  63254. });
  63255. /**
  63256. * Creates a depth stencil texture.
  63257. * This is only available in WebGL 2 or with the depth texture extension available.
  63258. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63259. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63260. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63261. */
  63262. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63263. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63264. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63265. if (generateStencil === void 0) { generateStencil = false; }
  63266. if (!this.getScene()) {
  63267. return;
  63268. }
  63269. var engine = this.getScene().getEngine();
  63270. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63271. bilinearFiltering: bilinearFiltering,
  63272. comparisonFunction: comparisonFunction,
  63273. generateStencil: generateStencil,
  63274. isCube: this.isCube
  63275. });
  63276. engine.setFrameBufferDepthStencilTexture(this);
  63277. };
  63278. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63279. if (size.ratio) {
  63280. this._sizeRatio = size.ratio;
  63281. this._size = {
  63282. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63283. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63284. };
  63285. }
  63286. else {
  63287. this._size = size;
  63288. }
  63289. };
  63290. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63291. get: function () {
  63292. return this._samples;
  63293. },
  63294. set: function (value) {
  63295. if (this._samples === value) {
  63296. return;
  63297. }
  63298. var scene = this.getScene();
  63299. if (!scene) {
  63300. return;
  63301. }
  63302. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63303. },
  63304. enumerable: true,
  63305. configurable: true
  63306. });
  63307. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63308. this._currentRefreshId = -1;
  63309. };
  63310. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63311. get: function () {
  63312. return this._refreshRate;
  63313. },
  63314. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63315. set: function (value) {
  63316. this._refreshRate = value;
  63317. this.resetRefreshCounter();
  63318. },
  63319. enumerable: true,
  63320. configurable: true
  63321. });
  63322. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63323. if (!this._postProcessManager) {
  63324. var scene = this.getScene();
  63325. if (!scene) {
  63326. return;
  63327. }
  63328. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63329. this._postProcesses = new Array();
  63330. }
  63331. this._postProcesses.push(postProcess);
  63332. this._postProcesses[0].autoClear = false;
  63333. };
  63334. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63335. if (!this._postProcesses) {
  63336. return;
  63337. }
  63338. if (dispose) {
  63339. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63340. var postProcess = _a[_i];
  63341. postProcess.dispose();
  63342. }
  63343. }
  63344. this._postProcesses = [];
  63345. };
  63346. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63347. if (!this._postProcesses) {
  63348. return;
  63349. }
  63350. var index = this._postProcesses.indexOf(postProcess);
  63351. if (index === -1) {
  63352. return;
  63353. }
  63354. this._postProcesses.splice(index, 1);
  63355. if (this._postProcesses.length > 0) {
  63356. this._postProcesses[0].autoClear = false;
  63357. }
  63358. };
  63359. RenderTargetTexture.prototype._shouldRender = function () {
  63360. if (this._currentRefreshId === -1) { // At least render once
  63361. this._currentRefreshId = 1;
  63362. return true;
  63363. }
  63364. if (this.refreshRate === this._currentRefreshId) {
  63365. this._currentRefreshId = 1;
  63366. return true;
  63367. }
  63368. this._currentRefreshId++;
  63369. return false;
  63370. };
  63371. RenderTargetTexture.prototype.getRenderSize = function () {
  63372. if (this._size.width) {
  63373. return this._size.width;
  63374. }
  63375. return this._size;
  63376. };
  63377. RenderTargetTexture.prototype.getRenderWidth = function () {
  63378. if (this._size.width) {
  63379. return this._size.width;
  63380. }
  63381. return this._size;
  63382. };
  63383. RenderTargetTexture.prototype.getRenderHeight = function () {
  63384. if (this._size.width) {
  63385. return this._size.height;
  63386. }
  63387. return this._size;
  63388. };
  63389. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63390. get: function () {
  63391. return true;
  63392. },
  63393. enumerable: true,
  63394. configurable: true
  63395. });
  63396. RenderTargetTexture.prototype.scale = function (ratio) {
  63397. var newSize = this.getRenderSize() * ratio;
  63398. this.resize(newSize);
  63399. };
  63400. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63401. if (this.isCube) {
  63402. return this._textureMatrix;
  63403. }
  63404. return _super.prototype.getReflectionTextureMatrix.call(this);
  63405. };
  63406. RenderTargetTexture.prototype.resize = function (size) {
  63407. this.releaseInternalTexture();
  63408. var scene = this.getScene();
  63409. if (!scene) {
  63410. return;
  63411. }
  63412. this._processSizeParameter(size);
  63413. if (this.isCube) {
  63414. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63415. }
  63416. else {
  63417. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63418. }
  63419. };
  63420. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63421. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63422. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63423. var scene = this.getScene();
  63424. if (!scene) {
  63425. return;
  63426. }
  63427. var engine = scene.getEngine();
  63428. if (this.useCameraPostProcesses !== undefined) {
  63429. useCameraPostProcess = this.useCameraPostProcesses;
  63430. }
  63431. if (this._waitingRenderList) {
  63432. this.renderList = [];
  63433. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63434. var id = this._waitingRenderList[index];
  63435. var mesh_1 = scene.getMeshByID(id);
  63436. if (mesh_1) {
  63437. this.renderList.push(mesh_1);
  63438. }
  63439. }
  63440. delete this._waitingRenderList;
  63441. }
  63442. // Is predicate defined?
  63443. if (this.renderListPredicate) {
  63444. if (this.renderList) {
  63445. this.renderList.splice(0); // Clear previous renderList
  63446. }
  63447. else {
  63448. this.renderList = [];
  63449. }
  63450. var scene = this.getScene();
  63451. if (!scene) {
  63452. return;
  63453. }
  63454. var sceneMeshes = scene.meshes;
  63455. for (var index = 0; index < sceneMeshes.length; index++) {
  63456. var mesh = sceneMeshes[index];
  63457. if (this.renderListPredicate(mesh)) {
  63458. this.renderList.push(mesh);
  63459. }
  63460. }
  63461. }
  63462. this.onBeforeBindObservable.notifyObservers(this);
  63463. // Set custom projection.
  63464. // Needs to be before binding to prevent changing the aspect ratio.
  63465. var camera;
  63466. if (this.activeCamera) {
  63467. camera = this.activeCamera;
  63468. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63469. if (this.activeCamera !== scene.activeCamera) {
  63470. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63471. }
  63472. }
  63473. else {
  63474. camera = scene.activeCamera;
  63475. if (camera) {
  63476. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63477. }
  63478. }
  63479. // Prepare renderingManager
  63480. this._renderingManager.reset();
  63481. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63482. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63483. var sceneRenderId = scene.getRenderId();
  63484. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63485. var mesh = currentRenderList[meshIndex];
  63486. if (mesh) {
  63487. if (!mesh.isReady(this.refreshRate === 0)) {
  63488. this.resetRefreshCounter();
  63489. continue;
  63490. }
  63491. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63492. var isMasked = void 0;
  63493. if (!this.renderList && camera) {
  63494. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63495. }
  63496. else {
  63497. isMasked = false;
  63498. }
  63499. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63500. mesh._activate(sceneRenderId);
  63501. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63502. var subMesh = mesh.subMeshes[subIndex];
  63503. scene._activeIndices.addCount(subMesh.indexCount, false);
  63504. this._renderingManager.dispatch(subMesh, mesh);
  63505. }
  63506. }
  63507. }
  63508. }
  63509. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63510. var particleSystem = scene.particleSystems[particleIndex];
  63511. var emitter = particleSystem.emitter;
  63512. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63513. continue;
  63514. }
  63515. if (currentRenderList.indexOf(emitter) >= 0) {
  63516. this._renderingManager.dispatchParticles(particleSystem);
  63517. }
  63518. }
  63519. if (this.isCube) {
  63520. for (var face = 0; face < 6; face++) {
  63521. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63522. scene.incrementRenderId();
  63523. scene.resetCachedMaterial();
  63524. }
  63525. }
  63526. else {
  63527. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63528. }
  63529. this.onAfterUnbindObservable.notifyObservers(this);
  63530. if (scene.activeCamera) {
  63531. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63532. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63533. }
  63534. engine.setViewport(scene.activeCamera.viewport);
  63535. }
  63536. scene.resetCachedMaterial();
  63537. };
  63538. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63539. var minimum = 128;
  63540. var x = renderDimension * scale;
  63541. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63542. // Ensure we don't exceed the render dimension (while staying POT)
  63543. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63544. };
  63545. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63546. var _this = this;
  63547. if (!this._texture) {
  63548. return;
  63549. }
  63550. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63551. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63552. });
  63553. };
  63554. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63555. var scene = this.getScene();
  63556. if (!scene) {
  63557. return;
  63558. }
  63559. var engine = scene.getEngine();
  63560. if (!this._texture) {
  63561. return;
  63562. }
  63563. // Bind
  63564. if (this._postProcessManager) {
  63565. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63566. }
  63567. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63568. if (this._texture) {
  63569. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63570. }
  63571. }
  63572. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63573. // Clear
  63574. if (this.onClearObservable.hasObservers()) {
  63575. this.onClearObservable.notifyObservers(engine);
  63576. }
  63577. else {
  63578. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63579. }
  63580. if (!this._doNotChangeAspectRatio) {
  63581. scene.updateTransformMatrix(true);
  63582. }
  63583. // Render
  63584. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63585. if (this._postProcessManager) {
  63586. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63587. }
  63588. else if (useCameraPostProcess) {
  63589. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63590. }
  63591. if (!this._doNotChangeAspectRatio) {
  63592. scene.updateTransformMatrix(true);
  63593. }
  63594. // Dump ?
  63595. if (dumpForDebug) {
  63596. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63597. }
  63598. // Unbind
  63599. if (!this.isCube || faceIndex === 5) {
  63600. if (this.isCube) {
  63601. if (faceIndex === 5) {
  63602. engine.generateMipMapsForCubemap(this._texture);
  63603. }
  63604. }
  63605. this.unbindFrameBuffer(engine, faceIndex);
  63606. }
  63607. else {
  63608. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63609. }
  63610. };
  63611. /**
  63612. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63613. * This allowed control for front to back rendering or reversly depending of the special needs.
  63614. *
  63615. * @param renderingGroupId The rendering group id corresponding to its index
  63616. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63617. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63618. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63619. */
  63620. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63621. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63622. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63623. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63624. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63625. };
  63626. /**
  63627. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63628. *
  63629. * @param renderingGroupId The rendering group id corresponding to its index
  63630. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63631. */
  63632. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63633. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63634. };
  63635. RenderTargetTexture.prototype.clone = function () {
  63636. var textureSize = this.getSize();
  63637. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  63638. // Base texture
  63639. newTexture.hasAlpha = this.hasAlpha;
  63640. newTexture.level = this.level;
  63641. // RenderTarget Texture
  63642. newTexture.coordinatesMode = this.coordinatesMode;
  63643. if (this.renderList) {
  63644. newTexture.renderList = this.renderList.slice(0);
  63645. }
  63646. return newTexture;
  63647. };
  63648. RenderTargetTexture.prototype.serialize = function () {
  63649. if (!this.name) {
  63650. return null;
  63651. }
  63652. var serializationObject = _super.prototype.serialize.call(this);
  63653. serializationObject.renderTargetSize = this.getRenderSize();
  63654. serializationObject.renderList = [];
  63655. if (this.renderList) {
  63656. for (var index = 0; index < this.renderList.length; index++) {
  63657. serializationObject.renderList.push(this.renderList[index].id);
  63658. }
  63659. }
  63660. return serializationObject;
  63661. };
  63662. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63663. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63664. var objBuffer = this.getInternalTexture();
  63665. var scene = this.getScene();
  63666. if (objBuffer && scene) {
  63667. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63668. }
  63669. };
  63670. RenderTargetTexture.prototype.dispose = function () {
  63671. if (this._postProcessManager) {
  63672. this._postProcessManager.dispose();
  63673. this._postProcessManager = null;
  63674. }
  63675. this.clearPostProcesses(true);
  63676. if (this._resizeObserver) {
  63677. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63678. this._resizeObserver = null;
  63679. }
  63680. this.renderList = null;
  63681. // Remove from custom render targets
  63682. var scene = this.getScene();
  63683. if (!scene) {
  63684. return;
  63685. }
  63686. var index = scene.customRenderTargets.indexOf(this);
  63687. if (index >= 0) {
  63688. scene.customRenderTargets.splice(index, 1);
  63689. }
  63690. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63691. var camera = _a[_i];
  63692. index = camera.customRenderTargets.indexOf(this);
  63693. if (index >= 0) {
  63694. camera.customRenderTargets.splice(index, 1);
  63695. }
  63696. }
  63697. _super.prototype.dispose.call(this);
  63698. };
  63699. RenderTargetTexture.prototype._rebuild = function () {
  63700. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63701. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63702. }
  63703. if (this._postProcessManager) {
  63704. this._postProcessManager._rebuild();
  63705. }
  63706. };
  63707. /**
  63708. * Clear the info related to rendering groups preventing retention point in material dispose.
  63709. */
  63710. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63711. if (this._renderingManager) {
  63712. this._renderingManager.freeRenderingGroups();
  63713. }
  63714. };
  63715. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63716. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63717. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63718. return RenderTargetTexture;
  63719. }(BABYLON.Texture));
  63720. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63721. })(BABYLON || (BABYLON = {}));
  63722. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63723. var BABYLON;
  63724. (function (BABYLON) {
  63725. ;
  63726. var MultiRenderTarget = /** @class */ (function (_super) {
  63727. __extends(MultiRenderTarget, _super);
  63728. function MultiRenderTarget(name, size, count, scene, options) {
  63729. var _this = this;
  63730. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63731. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63732. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63733. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63734. _this._engine = scene.getEngine();
  63735. if (!_this.isSupported) {
  63736. _this.dispose();
  63737. return;
  63738. }
  63739. var types = [];
  63740. var samplingModes = [];
  63741. for (var i = 0; i < count; i++) {
  63742. if (options && options.types && options.types[i] !== undefined) {
  63743. types.push(options.types[i]);
  63744. }
  63745. else {
  63746. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63747. }
  63748. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63749. samplingModes.push(options.samplingModes[i]);
  63750. }
  63751. else {
  63752. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63753. }
  63754. }
  63755. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63756. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63757. _this._size = size;
  63758. _this._multiRenderTargetOptions = {
  63759. samplingModes: samplingModes,
  63760. generateMipMaps: generateMipMaps,
  63761. generateDepthBuffer: generateDepthBuffer,
  63762. generateStencilBuffer: generateStencilBuffer,
  63763. generateDepthTexture: generateDepthTexture,
  63764. types: types,
  63765. textureCount: count
  63766. };
  63767. _this._createInternalTextures();
  63768. _this._createTextures();
  63769. return _this;
  63770. }
  63771. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63772. get: function () {
  63773. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63774. },
  63775. enumerable: true,
  63776. configurable: true
  63777. });
  63778. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63779. get: function () {
  63780. return this._textures;
  63781. },
  63782. enumerable: true,
  63783. configurable: true
  63784. });
  63785. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63786. get: function () {
  63787. return this._textures[this._textures.length - 1];
  63788. },
  63789. enumerable: true,
  63790. configurable: true
  63791. });
  63792. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63793. set: function (wrap) {
  63794. if (this._textures) {
  63795. for (var i = 0; i < this._textures.length; i++) {
  63796. this._textures[i].wrapU = wrap;
  63797. }
  63798. }
  63799. },
  63800. enumerable: true,
  63801. configurable: true
  63802. });
  63803. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63804. set: function (wrap) {
  63805. if (this._textures) {
  63806. for (var i = 0; i < this._textures.length; i++) {
  63807. this._textures[i].wrapV = wrap;
  63808. }
  63809. }
  63810. },
  63811. enumerable: true,
  63812. configurable: true
  63813. });
  63814. MultiRenderTarget.prototype._rebuild = function () {
  63815. this.releaseInternalTextures();
  63816. this._createInternalTextures();
  63817. for (var i = 0; i < this._internalTextures.length; i++) {
  63818. var texture = this._textures[i];
  63819. texture._texture = this._internalTextures[i];
  63820. }
  63821. // Keeps references to frame buffer and stencil/depth buffer
  63822. this._texture = this._internalTextures[0];
  63823. };
  63824. MultiRenderTarget.prototype._createInternalTextures = function () {
  63825. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63826. };
  63827. MultiRenderTarget.prototype._createTextures = function () {
  63828. this._textures = [];
  63829. for (var i = 0; i < this._internalTextures.length; i++) {
  63830. var texture = new BABYLON.Texture(null, this.getScene());
  63831. texture._texture = this._internalTextures[i];
  63832. this._textures.push(texture);
  63833. }
  63834. // Keeps references to frame buffer and stencil/depth buffer
  63835. this._texture = this._internalTextures[0];
  63836. };
  63837. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63838. get: function () {
  63839. return this._samples;
  63840. },
  63841. set: function (value) {
  63842. if (this._samples === value) {
  63843. return;
  63844. }
  63845. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63846. },
  63847. enumerable: true,
  63848. configurable: true
  63849. });
  63850. MultiRenderTarget.prototype.resize = function (size) {
  63851. this.releaseInternalTextures();
  63852. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63853. this._createInternalTextures();
  63854. };
  63855. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63856. var _this = this;
  63857. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63858. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63859. });
  63860. };
  63861. MultiRenderTarget.prototype.dispose = function () {
  63862. this.releaseInternalTextures();
  63863. _super.prototype.dispose.call(this);
  63864. };
  63865. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63866. if (!this._internalTextures) {
  63867. return;
  63868. }
  63869. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63870. if (this._internalTextures[i] !== undefined) {
  63871. this._internalTextures[i].dispose();
  63872. this._internalTextures.splice(i, 1);
  63873. }
  63874. }
  63875. };
  63876. return MultiRenderTarget;
  63877. }(BABYLON.RenderTargetTexture));
  63878. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63879. })(BABYLON || (BABYLON = {}));
  63880. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63881. var BABYLON;
  63882. (function (BABYLON) {
  63883. var MirrorTexture = /** @class */ (function (_super) {
  63884. __extends(MirrorTexture, _super);
  63885. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63886. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63888. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63889. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63890. _this.scene = scene;
  63891. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63892. _this._transformMatrix = BABYLON.Matrix.Zero();
  63893. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63894. _this._adaptiveBlurKernel = 0;
  63895. _this._blurKernelX = 0;
  63896. _this._blurKernelY = 0;
  63897. _this._blurRatio = 1.0;
  63898. _this.ignoreCameraViewport = true;
  63899. _this._updateGammaSpace();
  63900. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63901. _this._updateGammaSpace;
  63902. });
  63903. _this.onBeforeRenderObservable.add(function () {
  63904. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63905. _this._savedViewMatrix = scene.getViewMatrix();
  63906. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63907. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63908. scene.clipPlane = _this.mirrorPlane;
  63909. scene.getEngine().cullBackFaces = false;
  63910. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63911. });
  63912. _this.onAfterRenderObservable.add(function () {
  63913. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63914. scene.getEngine().cullBackFaces = true;
  63915. scene._mirroredCameraPosition = null;
  63916. delete scene.clipPlane;
  63917. });
  63918. return _this;
  63919. }
  63920. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63921. get: function () {
  63922. return this._blurRatio;
  63923. },
  63924. set: function (value) {
  63925. if (this._blurRatio === value) {
  63926. return;
  63927. }
  63928. this._blurRatio = value;
  63929. this._preparePostProcesses();
  63930. },
  63931. enumerable: true,
  63932. configurable: true
  63933. });
  63934. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63935. set: function (value) {
  63936. this._adaptiveBlurKernel = value;
  63937. this._autoComputeBlurKernel();
  63938. },
  63939. enumerable: true,
  63940. configurable: true
  63941. });
  63942. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63943. set: function (value) {
  63944. this.blurKernelX = value;
  63945. this.blurKernelY = value;
  63946. },
  63947. enumerable: true,
  63948. configurable: true
  63949. });
  63950. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63951. get: function () {
  63952. return this._blurKernelX;
  63953. },
  63954. set: function (value) {
  63955. if (this._blurKernelX === value) {
  63956. return;
  63957. }
  63958. this._blurKernelX = value;
  63959. this._preparePostProcesses();
  63960. },
  63961. enumerable: true,
  63962. configurable: true
  63963. });
  63964. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63965. get: function () {
  63966. return this._blurKernelY;
  63967. },
  63968. set: function (value) {
  63969. if (this._blurKernelY === value) {
  63970. return;
  63971. }
  63972. this._blurKernelY = value;
  63973. this._preparePostProcesses();
  63974. },
  63975. enumerable: true,
  63976. configurable: true
  63977. });
  63978. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63979. var engine = this.getScene().getEngine();
  63980. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63981. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63982. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63983. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63984. };
  63985. MirrorTexture.prototype._onRatioRescale = function () {
  63986. if (this._sizeRatio) {
  63987. this.resize(this._initialSizeParameter);
  63988. if (!this._adaptiveBlurKernel) {
  63989. this._preparePostProcesses();
  63990. }
  63991. }
  63992. if (this._adaptiveBlurKernel) {
  63993. this._autoComputeBlurKernel();
  63994. }
  63995. };
  63996. MirrorTexture.prototype._updateGammaSpace = function () {
  63997. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63998. };
  63999. MirrorTexture.prototype._preparePostProcesses = function () {
  64000. this.clearPostProcesses(true);
  64001. if (this._blurKernelX && this._blurKernelY) {
  64002. var engine = this.getScene().getEngine();
  64003. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64004. 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);
  64005. this._blurX.autoClear = false;
  64006. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64007. this._blurX.inputTexture = this._texture;
  64008. }
  64009. else {
  64010. this._blurX.alwaysForcePOT = true;
  64011. }
  64012. 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);
  64013. this._blurY.autoClear = false;
  64014. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64015. this.addPostProcess(this._blurX);
  64016. this.addPostProcess(this._blurY);
  64017. }
  64018. else {
  64019. if (this._blurY) {
  64020. this.removePostProcess(this._blurY);
  64021. this._blurY.dispose();
  64022. this._blurY = null;
  64023. }
  64024. if (this._blurX) {
  64025. this.removePostProcess(this._blurX);
  64026. this._blurX.dispose();
  64027. this._blurX = null;
  64028. }
  64029. }
  64030. };
  64031. MirrorTexture.prototype.clone = function () {
  64032. var scene = this.getScene();
  64033. if (!scene) {
  64034. return this;
  64035. }
  64036. var textureSize = this.getSize();
  64037. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64038. // Base texture
  64039. newTexture.hasAlpha = this.hasAlpha;
  64040. newTexture.level = this.level;
  64041. // Mirror Texture
  64042. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64043. if (this.renderList) {
  64044. newTexture.renderList = this.renderList.slice(0);
  64045. }
  64046. return newTexture;
  64047. };
  64048. MirrorTexture.prototype.serialize = function () {
  64049. if (!this.name) {
  64050. return null;
  64051. }
  64052. var serializationObject = _super.prototype.serialize.call(this);
  64053. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64054. return serializationObject;
  64055. };
  64056. MirrorTexture.prototype.dispose = function () {
  64057. _super.prototype.dispose.call(this);
  64058. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64059. };
  64060. return MirrorTexture;
  64061. }(BABYLON.RenderTargetTexture));
  64062. BABYLON.MirrorTexture = MirrorTexture;
  64063. })(BABYLON || (BABYLON = {}));
  64064. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64065. var BABYLON;
  64066. (function (BABYLON) {
  64067. /**
  64068. * Creates a refraction texture used by refraction channel of the standard material.
  64069. * @param name the texture name
  64070. * @param size size of the underlying texture
  64071. * @param scene root scene
  64072. */
  64073. var RefractionTexture = /** @class */ (function (_super) {
  64074. __extends(RefractionTexture, _super);
  64075. function RefractionTexture(name, size, scene, generateMipMaps) {
  64076. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64077. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64078. _this.depth = 2.0;
  64079. _this.onBeforeRenderObservable.add(function () {
  64080. scene.clipPlane = _this.refractionPlane;
  64081. });
  64082. _this.onAfterRenderObservable.add(function () {
  64083. delete scene.clipPlane;
  64084. });
  64085. return _this;
  64086. }
  64087. RefractionTexture.prototype.clone = function () {
  64088. var scene = this.getScene();
  64089. if (!scene) {
  64090. return this;
  64091. }
  64092. var textureSize = this.getSize();
  64093. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64094. // Base texture
  64095. newTexture.hasAlpha = this.hasAlpha;
  64096. newTexture.level = this.level;
  64097. // Refraction Texture
  64098. newTexture.refractionPlane = this.refractionPlane.clone();
  64099. if (this.renderList) {
  64100. newTexture.renderList = this.renderList.slice(0);
  64101. }
  64102. newTexture.depth = this.depth;
  64103. return newTexture;
  64104. };
  64105. RefractionTexture.prototype.serialize = function () {
  64106. if (!this.name) {
  64107. return null;
  64108. }
  64109. var serializationObject = _super.prototype.serialize.call(this);
  64110. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64111. serializationObject.depth = this.depth;
  64112. return serializationObject;
  64113. };
  64114. return RefractionTexture;
  64115. }(BABYLON.RenderTargetTexture));
  64116. BABYLON.RefractionTexture = RefractionTexture;
  64117. })(BABYLON || (BABYLON = {}));
  64118. //# sourceMappingURL=babylon.refractionTexture.js.map
  64119. var BABYLON;
  64120. (function (BABYLON) {
  64121. /**
  64122. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64123. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64124. */
  64125. var DynamicTexture = /** @class */ (function (_super) {
  64126. __extends(DynamicTexture, _super);
  64127. /**
  64128. * Creates a {BABYLON.DynamicTexture}
  64129. * @param name defines the name of the texture
  64130. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  64131. * @param scene defines the scene where you want the texture
  64132. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64133. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64134. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64135. */
  64136. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64137. if (scene === void 0) { scene = null; }
  64138. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64139. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64140. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64141. _this.name = name;
  64142. _this._engine = _this.getScene().getEngine();
  64143. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64144. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64145. _this._generateMipMaps = generateMipMaps;
  64146. if (options.getContext) {
  64147. _this._canvas = options;
  64148. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64149. }
  64150. else {
  64151. _this._canvas = document.createElement("canvas");
  64152. if (options.width || options.width === 0) {
  64153. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64154. }
  64155. else {
  64156. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64157. }
  64158. }
  64159. var textureSize = _this.getSize();
  64160. _this._canvas.width = textureSize.width;
  64161. _this._canvas.height = textureSize.height;
  64162. _this._context = _this._canvas.getContext("2d");
  64163. return _this;
  64164. }
  64165. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64166. /**
  64167. * Gets the current state of canRescale
  64168. */
  64169. get: function () {
  64170. return true;
  64171. },
  64172. enumerable: true,
  64173. configurable: true
  64174. });
  64175. DynamicTexture.prototype._recreate = function (textureSize) {
  64176. this._canvas.width = textureSize.width;
  64177. this._canvas.height = textureSize.height;
  64178. this.releaseInternalTexture();
  64179. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64180. };
  64181. /**
  64182. * Scales the texture
  64183. * @param ratio the scale factor to apply to both width and height
  64184. */
  64185. DynamicTexture.prototype.scale = function (ratio) {
  64186. var textureSize = this.getSize();
  64187. textureSize.width *= ratio;
  64188. textureSize.height *= ratio;
  64189. this._recreate(textureSize);
  64190. };
  64191. /**
  64192. * Resizes the texture
  64193. * @param width the new width
  64194. * @param height the new height
  64195. */
  64196. DynamicTexture.prototype.scaleTo = function (width, height) {
  64197. var textureSize = this.getSize();
  64198. textureSize.width = width;
  64199. textureSize.height = height;
  64200. this._recreate(textureSize);
  64201. };
  64202. /**
  64203. * Gets the context of the canvas used by the texture
  64204. * @returns the canvas context of the dynamic texture
  64205. */
  64206. DynamicTexture.prototype.getContext = function () {
  64207. return this._context;
  64208. };
  64209. /**
  64210. * Clears the texture
  64211. */
  64212. DynamicTexture.prototype.clear = function () {
  64213. var size = this.getSize();
  64214. this._context.fillRect(0, 0, size.width, size.height);
  64215. };
  64216. /**
  64217. * Updates the texture
  64218. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64219. */
  64220. DynamicTexture.prototype.update = function (invertY) {
  64221. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64222. };
  64223. /**
  64224. * Draws text onto the texture
  64225. * @param text defines the text to be drawn
  64226. * @param x defines the placement of the text from the left
  64227. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64228. * @param font defines the font to be used with font-style, font-size, font-name
  64229. * @param color defines the color used for the text
  64230. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64231. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64232. * @param update defines whether texture is immediately update (default is true)
  64233. */
  64234. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64235. if (update === void 0) { update = true; }
  64236. var size = this.getSize();
  64237. if (clearColor) {
  64238. this._context.fillStyle = clearColor;
  64239. this._context.fillRect(0, 0, size.width, size.height);
  64240. }
  64241. this._context.font = font;
  64242. if (x === null || x === undefined) {
  64243. var textSize = this._context.measureText(text);
  64244. x = (size.width - textSize.width) / 2;
  64245. }
  64246. if (y === null || y === undefined) {
  64247. var fontSize = parseInt((font.replace(/\D/g, '')));
  64248. y = (size.height / 2) + (fontSize / 3.65);
  64249. }
  64250. this._context.fillStyle = color;
  64251. this._context.fillText(text, x, y);
  64252. if (update) {
  64253. this.update(invertY);
  64254. }
  64255. };
  64256. /**
  64257. * Clones the texture
  64258. * @returns the clone of the texture.
  64259. */
  64260. DynamicTexture.prototype.clone = function () {
  64261. var scene = this.getScene();
  64262. if (!scene) {
  64263. return this;
  64264. }
  64265. var textureSize = this.getSize();
  64266. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64267. // Base texture
  64268. newTexture.hasAlpha = this.hasAlpha;
  64269. newTexture.level = this.level;
  64270. // Dynamic Texture
  64271. newTexture.wrapU = this.wrapU;
  64272. newTexture.wrapV = this.wrapV;
  64273. return newTexture;
  64274. };
  64275. /** @hidden */
  64276. DynamicTexture.prototype._rebuild = function () {
  64277. this.update();
  64278. };
  64279. return DynamicTexture;
  64280. }(BABYLON.Texture));
  64281. BABYLON.DynamicTexture = DynamicTexture;
  64282. })(BABYLON || (BABYLON = {}));
  64283. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64284. var BABYLON;
  64285. (function (BABYLON) {
  64286. var VideoTexture = /** @class */ (function (_super) {
  64287. __extends(VideoTexture, _super);
  64288. /**
  64289. * Creates a video texture.
  64290. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64291. * @param {string | null} name optional name, will detect from video source, if not defined
  64292. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64293. * @param {BABYLON.Scene} scene is obviously the current scene.
  64294. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64295. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64296. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64297. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64298. */
  64299. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64300. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64301. if (invertY === void 0) { invertY = false; }
  64302. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64303. if (settings === void 0) { settings = {
  64304. autoPlay: true,
  64305. loop: true,
  64306. autoUpdateTexture: true,
  64307. }; }
  64308. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64309. _this._stillImageCaptured = false;
  64310. _this._createInternalTexture = function () {
  64311. if (_this._texture != null) {
  64312. return;
  64313. }
  64314. if (!_this._engine.needPOTTextures ||
  64315. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64316. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64317. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64318. }
  64319. else {
  64320. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64321. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64322. _this._generateMipMaps = false;
  64323. }
  64324. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64325. if (!_this.video.autoplay) {
  64326. var oldHandler_1 = _this.video.onplaying;
  64327. _this.video.onplaying = function () {
  64328. _this.video.onplaying = oldHandler_1;
  64329. _this._texture.isReady = true;
  64330. _this._updateInternalTexture();
  64331. _this.video.pause();
  64332. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64333. _this.onLoadObservable.notifyObservers(_this);
  64334. }
  64335. };
  64336. _this.video.play();
  64337. }
  64338. else {
  64339. _this._texture.isReady = true;
  64340. _this._updateInternalTexture();
  64341. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64342. _this.onLoadObservable.notifyObservers(_this);
  64343. }
  64344. }
  64345. };
  64346. _this.reset = function () {
  64347. if (_this._texture == null) {
  64348. return;
  64349. }
  64350. _this._texture.dispose();
  64351. _this._texture = null;
  64352. };
  64353. _this._updateInternalTexture = function (e) {
  64354. if (_this._texture == null || !_this._texture.isReady) {
  64355. return;
  64356. }
  64357. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64358. return;
  64359. }
  64360. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64361. };
  64362. _this._engine = _this.getScene().getEngine();
  64363. _this._generateMipMaps = generateMipMaps;
  64364. _this._samplingMode = samplingMode;
  64365. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64366. _this.name = name || _this._getName(src);
  64367. _this.video = _this._getVideo(src);
  64368. if (settings.autoPlay !== undefined) {
  64369. _this.video.autoplay = settings.autoPlay;
  64370. }
  64371. if (settings.loop !== undefined) {
  64372. _this.video.loop = settings.loop;
  64373. }
  64374. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64375. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64376. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64377. _this.video.addEventListener("emptied", _this.reset);
  64378. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64379. _this._createInternalTexture();
  64380. }
  64381. return _this;
  64382. }
  64383. VideoTexture.prototype._getName = function (src) {
  64384. if (src instanceof HTMLVideoElement) {
  64385. return src.currentSrc;
  64386. }
  64387. if (typeof src === "object") {
  64388. return src.toString();
  64389. }
  64390. return src;
  64391. };
  64392. ;
  64393. VideoTexture.prototype._getVideo = function (src) {
  64394. if (src instanceof HTMLVideoElement) {
  64395. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64396. return src;
  64397. }
  64398. var video = document.createElement("video");
  64399. if (typeof src === "string") {
  64400. BABYLON.Tools.SetCorsBehavior(src, video);
  64401. video.src = src;
  64402. }
  64403. else {
  64404. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64405. src.forEach(function (url) {
  64406. var source = document.createElement("source");
  64407. source.src = url;
  64408. video.appendChild(source);
  64409. });
  64410. }
  64411. return video;
  64412. };
  64413. ;
  64414. /**
  64415. * Internal method to initiate `update`.
  64416. */
  64417. VideoTexture.prototype._rebuild = function () {
  64418. this.update();
  64419. };
  64420. /**
  64421. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64422. */
  64423. VideoTexture.prototype.update = function () {
  64424. if (!this.autoUpdateTexture) {
  64425. // Expecting user to call `updateTexture` manually
  64426. return;
  64427. }
  64428. this.updateTexture(true);
  64429. };
  64430. /**
  64431. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64432. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64433. */
  64434. VideoTexture.prototype.updateTexture = function (isVisible) {
  64435. if (!isVisible) {
  64436. return;
  64437. }
  64438. if (this.video.paused && this._stillImageCaptured) {
  64439. return;
  64440. }
  64441. this._stillImageCaptured = true;
  64442. this._updateInternalTexture();
  64443. };
  64444. /**
  64445. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64446. * @param url New url.
  64447. */
  64448. VideoTexture.prototype.updateURL = function (url) {
  64449. this.video.src = url;
  64450. };
  64451. VideoTexture.prototype.dispose = function () {
  64452. _super.prototype.dispose.call(this);
  64453. this.video.removeEventListener("canplay", this._createInternalTexture);
  64454. this.video.removeEventListener("paused", this._updateInternalTexture);
  64455. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64456. this.video.removeEventListener("emptied", this.reset);
  64457. this.video.pause();
  64458. };
  64459. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64460. var video = document.createElement("video");
  64461. var constraintsDeviceId;
  64462. if (constraints && constraints.deviceId) {
  64463. constraintsDeviceId = {
  64464. exact: constraints.deviceId,
  64465. };
  64466. }
  64467. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64468. if (navigator.mediaDevices) {
  64469. navigator.mediaDevices.getUserMedia({ video: constraints })
  64470. .then(function (stream) {
  64471. if (video.mozSrcObject !== undefined) {
  64472. // hack for Firefox < 19
  64473. video.mozSrcObject = stream;
  64474. }
  64475. else {
  64476. video.srcObject = stream;
  64477. }
  64478. var onPlaying = function () {
  64479. if (onReady) {
  64480. onReady(new VideoTexture("video", video, scene, true, true));
  64481. }
  64482. video.removeEventListener("playing", onPlaying);
  64483. };
  64484. video.addEventListener("playing", onPlaying);
  64485. video.play();
  64486. })
  64487. .catch(function (err) {
  64488. BABYLON.Tools.Error(err.name);
  64489. });
  64490. }
  64491. else {
  64492. navigator.getUserMedia =
  64493. navigator.getUserMedia ||
  64494. navigator.webkitGetUserMedia ||
  64495. navigator.mozGetUserMedia ||
  64496. navigator.msGetUserMedia;
  64497. if (navigator.getUserMedia) {
  64498. navigator.getUserMedia({
  64499. video: {
  64500. deviceId: constraintsDeviceId,
  64501. width: {
  64502. min: (constraints && constraints.minWidth) || 256,
  64503. max: (constraints && constraints.maxWidth) || 640,
  64504. },
  64505. height: {
  64506. min: (constraints && constraints.minHeight) || 256,
  64507. max: (constraints && constraints.maxHeight) || 480,
  64508. },
  64509. },
  64510. }, function (stream) {
  64511. if (video.mozSrcObject !== undefined) {
  64512. // hack for Firefox < 19
  64513. video.mozSrcObject = stream;
  64514. }
  64515. else {
  64516. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64517. }
  64518. video.play();
  64519. if (onReady) {
  64520. onReady(new VideoTexture("video", video, scene, true, true));
  64521. }
  64522. }, function (e) {
  64523. BABYLON.Tools.Error(e.name);
  64524. });
  64525. }
  64526. }
  64527. };
  64528. return VideoTexture;
  64529. }(BABYLON.Texture));
  64530. BABYLON.VideoTexture = VideoTexture;
  64531. })(BABYLON || (BABYLON = {}));
  64532. //# sourceMappingURL=babylon.videoTexture.js.map
  64533. var BABYLON;
  64534. (function (BABYLON) {
  64535. var RawTexture = /** @class */ (function (_super) {
  64536. __extends(RawTexture, _super);
  64537. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64538. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64539. if (invertY === void 0) { invertY = false; }
  64540. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64541. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64542. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64543. _this.format = format;
  64544. _this._engine = scene.getEngine();
  64545. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64546. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64547. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64548. return _this;
  64549. }
  64550. RawTexture.prototype.update = function (data) {
  64551. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64552. };
  64553. // Statics
  64554. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64555. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64556. if (invertY === void 0) { invertY = false; }
  64557. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64558. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64559. };
  64560. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64561. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64562. if (invertY === void 0) { invertY = false; }
  64563. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64564. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64565. };
  64566. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64567. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64568. if (invertY === void 0) { invertY = false; }
  64569. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64570. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64571. };
  64572. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64573. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64574. if (invertY === void 0) { invertY = false; }
  64575. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64576. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64577. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64578. };
  64579. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64580. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64581. if (invertY === void 0) { invertY = false; }
  64582. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64583. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64584. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64585. };
  64586. return RawTexture;
  64587. }(BABYLON.Texture));
  64588. BABYLON.RawTexture = RawTexture;
  64589. })(BABYLON || (BABYLON = {}));
  64590. //# sourceMappingURL=babylon.rawTexture.js.map
  64591. var BABYLON;
  64592. (function (BABYLON) {
  64593. /**
  64594. * Class used to store 3D textures containing user data
  64595. */
  64596. var RawTexture3D = /** @class */ (function (_super) {
  64597. __extends(RawTexture3D, _super);
  64598. /**
  64599. * Create a new RawTexture3D
  64600. * @param data defines the data of the texture
  64601. * @param width defines the width of the texture
  64602. * @param height defines the height of the texture
  64603. * @param depth defines the depth of the texture
  64604. * @param format defines the texture format to use
  64605. * @param scene defines the hosting scene
  64606. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64607. * @param invertY defines if texture must be stored with Y axis inverted
  64608. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64609. */
  64610. function RawTexture3D(data, width, height, depth,
  64611. /** Gets or sets the texture format to use*/
  64612. format, scene, generateMipMaps, invertY, samplingMode) {
  64613. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64614. if (invertY === void 0) { invertY = false; }
  64615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64616. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64617. _this.format = format;
  64618. _this._engine = scene.getEngine();
  64619. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64620. _this.is3D = true;
  64621. return _this;
  64622. }
  64623. /**
  64624. * Update the texture with new data
  64625. * @param data defines the data to store in the texture
  64626. */
  64627. RawTexture3D.prototype.update = function (data) {
  64628. if (!this._texture) {
  64629. return;
  64630. }
  64631. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64632. };
  64633. return RawTexture3D;
  64634. }(BABYLON.Texture));
  64635. BABYLON.RawTexture3D = RawTexture3D;
  64636. })(BABYLON || (BABYLON = {}));
  64637. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64638. var BABYLON;
  64639. (function (BABYLON) {
  64640. /**
  64641. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64642. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64643. */
  64644. var PostProcess = /** @class */ (function () {
  64645. /**
  64646. * Creates a new instance PostProcess
  64647. * @param name The name of the PostProcess.
  64648. * @param fragmentUrl The url of the fragment shader to be used.
  64649. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64650. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64651. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64652. * @param camera The camera to apply the render pass to.
  64653. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64654. * @param engine The engine which the post process will be applied. (default: current engine)
  64655. * @param reusable If the post process can be reused on the same frame. (default: false)
  64656. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64657. * @param textureType Type of textures used when performing the post process. (default: 0)
  64658. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64659. * @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
  64660. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64661. */
  64662. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64663. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64664. if (defines === void 0) { defines = null; }
  64665. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64666. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64667. if (blockCompilation === void 0) { blockCompilation = false; }
  64668. this.name = name;
  64669. /**
  64670. * Width of the texture to apply the post process on
  64671. */
  64672. this.width = -1;
  64673. /**
  64674. * Height of the texture to apply the post process on
  64675. */
  64676. this.height = -1;
  64677. /**
  64678. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64679. */
  64680. this._outputTexture = null;
  64681. /**
  64682. * If the buffer needs to be cleared before applying the post process. (default: true)
  64683. * Should be set to false if shader will overwrite all previous pixels.
  64684. */
  64685. this.autoClear = true;
  64686. /**
  64687. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64688. */
  64689. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64690. /**
  64691. * Animations to be used for the post processing
  64692. */
  64693. this.animations = new Array();
  64694. /**
  64695. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64696. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64697. */
  64698. this.enablePixelPerfectMode = false;
  64699. /**
  64700. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64701. */
  64702. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64703. /**
  64704. * Force textures to be a power of two (default: false)
  64705. */
  64706. this.alwaysForcePOT = false;
  64707. /**
  64708. * Number of sample textures (default: 1)
  64709. */
  64710. this.samples = 1;
  64711. /**
  64712. * Modify the scale of the post process to be the same as the viewport (default: false)
  64713. */
  64714. this.adaptScaleToCurrentViewport = false;
  64715. this._reusable = false;
  64716. /**
  64717. * Smart array of input and output textures for the post process.
  64718. */
  64719. this._textures = new BABYLON.SmartArray(2);
  64720. /**
  64721. * The index in _textures that corresponds to the output texture.
  64722. */
  64723. this._currentRenderTextureInd = 0;
  64724. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64725. this._texelSize = BABYLON.Vector2.Zero();
  64726. // Events
  64727. /**
  64728. * An event triggered when the postprocess is activated.
  64729. */
  64730. this.onActivateObservable = new BABYLON.Observable();
  64731. /**
  64732. * An event triggered when the postprocess changes its size.
  64733. */
  64734. this.onSizeChangedObservable = new BABYLON.Observable();
  64735. /**
  64736. * An event triggered when the postprocess applies its effect.
  64737. */
  64738. this.onApplyObservable = new BABYLON.Observable();
  64739. /**
  64740. * An event triggered before rendering the postprocess
  64741. */
  64742. this.onBeforeRenderObservable = new BABYLON.Observable();
  64743. /**
  64744. * An event triggered after rendering the postprocess
  64745. */
  64746. this.onAfterRenderObservable = new BABYLON.Observable();
  64747. if (camera != null) {
  64748. this._camera = camera;
  64749. this._scene = camera.getScene();
  64750. camera.attachPostProcess(this);
  64751. this._engine = this._scene.getEngine();
  64752. this._scene.postProcesses.push(this);
  64753. }
  64754. else if (engine) {
  64755. this._engine = engine;
  64756. this._engine.postProcesses.push(this);
  64757. }
  64758. this._options = options;
  64759. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64760. this._reusable = reusable || false;
  64761. this._textureType = textureType;
  64762. this._samplers = samplers || [];
  64763. this._samplers.push("textureSampler");
  64764. this._fragmentUrl = fragmentUrl;
  64765. this._vertexUrl = vertexUrl;
  64766. this._parameters = parameters || [];
  64767. this._parameters.push("scale");
  64768. this._indexParameters = indexParameters;
  64769. if (!blockCompilation) {
  64770. this.updateEffect(defines);
  64771. }
  64772. }
  64773. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64774. /**
  64775. * A function that is added to the onActivateObservable
  64776. */
  64777. set: function (callback) {
  64778. if (this._onActivateObserver) {
  64779. this.onActivateObservable.remove(this._onActivateObserver);
  64780. }
  64781. if (callback) {
  64782. this._onActivateObserver = this.onActivateObservable.add(callback);
  64783. }
  64784. },
  64785. enumerable: true,
  64786. configurable: true
  64787. });
  64788. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64789. /**
  64790. * A function that is added to the onSizeChangedObservable
  64791. */
  64792. set: function (callback) {
  64793. if (this._onSizeChangedObserver) {
  64794. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64795. }
  64796. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64797. },
  64798. enumerable: true,
  64799. configurable: true
  64800. });
  64801. Object.defineProperty(PostProcess.prototype, "onApply", {
  64802. /**
  64803. * A function that is added to the onApplyObservable
  64804. */
  64805. set: function (callback) {
  64806. if (this._onApplyObserver) {
  64807. this.onApplyObservable.remove(this._onApplyObserver);
  64808. }
  64809. this._onApplyObserver = this.onApplyObservable.add(callback);
  64810. },
  64811. enumerable: true,
  64812. configurable: true
  64813. });
  64814. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64815. /**
  64816. * A function that is added to the onBeforeRenderObservable
  64817. */
  64818. set: function (callback) {
  64819. if (this._onBeforeRenderObserver) {
  64820. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64821. }
  64822. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64823. },
  64824. enumerable: true,
  64825. configurable: true
  64826. });
  64827. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64828. /**
  64829. * A function that is added to the onAfterRenderObservable
  64830. */
  64831. set: function (callback) {
  64832. if (this._onAfterRenderObserver) {
  64833. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64834. }
  64835. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64836. },
  64837. enumerable: true,
  64838. configurable: true
  64839. });
  64840. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64841. /**
  64842. * 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
  64843. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64844. */
  64845. get: function () {
  64846. return this._textures.data[this._currentRenderTextureInd];
  64847. },
  64848. set: function (value) {
  64849. this._forcedOutputTexture = value;
  64850. },
  64851. enumerable: true,
  64852. configurable: true
  64853. });
  64854. /**
  64855. * Gets the camera which post process is applied to.
  64856. * @returns The camera the post process is applied to.
  64857. */
  64858. PostProcess.prototype.getCamera = function () {
  64859. return this._camera;
  64860. };
  64861. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64862. /**
  64863. * Gets the texel size of the postprocess.
  64864. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64865. */
  64866. get: function () {
  64867. if (this._shareOutputWithPostProcess) {
  64868. return this._shareOutputWithPostProcess.texelSize;
  64869. }
  64870. if (this._forcedOutputTexture) {
  64871. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64872. }
  64873. return this._texelSize;
  64874. },
  64875. enumerable: true,
  64876. configurable: true
  64877. });
  64878. /**
  64879. * Gets the engine which this post process belongs to.
  64880. * @returns The engine the post process was enabled with.
  64881. */
  64882. PostProcess.prototype.getEngine = function () {
  64883. return this._engine;
  64884. };
  64885. /**
  64886. * The effect that is created when initializing the post process.
  64887. * @returns The created effect corrisponding the the postprocess.
  64888. */
  64889. PostProcess.prototype.getEffect = function () {
  64890. return this._effect;
  64891. };
  64892. /**
  64893. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64894. * @param postProcess The post process to share the output with.
  64895. * @returns This post process.
  64896. */
  64897. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64898. this._disposeTextures();
  64899. this._shareOutputWithPostProcess = postProcess;
  64900. return this;
  64901. };
  64902. /**
  64903. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64904. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64905. */
  64906. PostProcess.prototype.useOwnOutput = function () {
  64907. if (this._textures.length == 0) {
  64908. this._textures = new BABYLON.SmartArray(2);
  64909. }
  64910. this._shareOutputWithPostProcess = null;
  64911. };
  64912. /**
  64913. * Updates the effect with the current post process compile time values and recompiles the shader.
  64914. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64915. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64916. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64917. * @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
  64918. * @param onCompiled Called when the shader has been compiled.
  64919. * @param onError Called if there is an error when compiling a shader.
  64920. */
  64921. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64922. if (defines === void 0) { defines = null; }
  64923. if (uniforms === void 0) { uniforms = null; }
  64924. if (samplers === void 0) { samplers = null; }
  64925. 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);
  64926. };
  64927. /**
  64928. * The post process is reusable if it can be used multiple times within one frame.
  64929. * @returns If the post process is reusable
  64930. */
  64931. PostProcess.prototype.isReusable = function () {
  64932. return this._reusable;
  64933. };
  64934. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64935. PostProcess.prototype.markTextureDirty = function () {
  64936. this.width = -1;
  64937. };
  64938. /**
  64939. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64940. * 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.
  64941. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64942. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64943. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64944. * @returns The target texture that was bound to be written to.
  64945. */
  64946. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64947. var _this = this;
  64948. if (sourceTexture === void 0) { sourceTexture = null; }
  64949. camera = camera || this._camera;
  64950. var scene = camera.getScene();
  64951. var engine = scene.getEngine();
  64952. var maxSize = engine.getCaps().maxTextureSize;
  64953. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64954. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64955. // 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
  64956. var webVRCamera = camera.parent;
  64957. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64958. requiredWidth /= 2;
  64959. }
  64960. var desiredWidth = (this._options.width || requiredWidth);
  64961. var desiredHeight = this._options.height || requiredHeight;
  64962. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64963. if (this.adaptScaleToCurrentViewport) {
  64964. var currentViewport = engine.currentViewport;
  64965. if (currentViewport) {
  64966. desiredWidth *= currentViewport.width;
  64967. desiredHeight *= currentViewport.height;
  64968. }
  64969. }
  64970. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64971. if (!this._options.width) {
  64972. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64973. }
  64974. if (!this._options.height) {
  64975. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64976. }
  64977. }
  64978. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64979. if (this._textures.length > 0) {
  64980. for (var i = 0; i < this._textures.length; i++) {
  64981. this._engine._releaseTexture(this._textures.data[i]);
  64982. }
  64983. this._textures.reset();
  64984. }
  64985. this.width = desiredWidth;
  64986. this.height = desiredHeight;
  64987. var textureSize = { width: this.width, height: this.height };
  64988. var textureOptions = {
  64989. generateMipMaps: false,
  64990. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64991. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64992. samplingMode: this.renderTargetSamplingMode,
  64993. type: this._textureType
  64994. };
  64995. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64996. if (this._reusable) {
  64997. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64998. }
  64999. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65000. this.onSizeChangedObservable.notifyObservers(this);
  65001. }
  65002. this._textures.forEach(function (texture) {
  65003. if (texture.samples !== _this.samples) {
  65004. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65005. }
  65006. });
  65007. }
  65008. var target;
  65009. if (this._shareOutputWithPostProcess) {
  65010. target = this._shareOutputWithPostProcess.inputTexture;
  65011. }
  65012. else if (this._forcedOutputTexture) {
  65013. target = this._forcedOutputTexture;
  65014. this.width = this._forcedOutputTexture.width;
  65015. this.height = this._forcedOutputTexture.height;
  65016. }
  65017. else {
  65018. target = this.inputTexture;
  65019. }
  65020. // Bind the input of this post process to be used as the output of the previous post process.
  65021. if (this.enablePixelPerfectMode) {
  65022. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65023. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65024. }
  65025. else {
  65026. this._scaleRatio.copyFromFloats(1, 1);
  65027. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65028. }
  65029. this.onActivateObservable.notifyObservers(camera);
  65030. // Clear
  65031. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65032. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65033. }
  65034. if (this._reusable) {
  65035. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65036. }
  65037. return target;
  65038. };
  65039. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65040. /**
  65041. * If the post process is supported.
  65042. */
  65043. get: function () {
  65044. return this._effect.isSupported;
  65045. },
  65046. enumerable: true,
  65047. configurable: true
  65048. });
  65049. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65050. /**
  65051. * The aspect ratio of the output texture.
  65052. */
  65053. get: function () {
  65054. if (this._shareOutputWithPostProcess) {
  65055. return this._shareOutputWithPostProcess.aspectRatio;
  65056. }
  65057. if (this._forcedOutputTexture) {
  65058. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65059. }
  65060. return this.width / this.height;
  65061. },
  65062. enumerable: true,
  65063. configurable: true
  65064. });
  65065. /**
  65066. * Get a value indicating if the post-process is ready to be used
  65067. * @returns true if the post-process is ready (shader is compiled)
  65068. */
  65069. PostProcess.prototype.isReady = function () {
  65070. return this._effect && this._effect.isReady();
  65071. };
  65072. /**
  65073. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65074. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65075. */
  65076. PostProcess.prototype.apply = function () {
  65077. // Check
  65078. if (!this._effect || !this._effect.isReady())
  65079. return null;
  65080. // States
  65081. this._engine.enableEffect(this._effect);
  65082. this._engine.setState(false);
  65083. this._engine.setDepthBuffer(false);
  65084. this._engine.setDepthWrite(false);
  65085. // Alpha
  65086. this._engine.setAlphaMode(this.alphaMode);
  65087. if (this.alphaConstants) {
  65088. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65089. }
  65090. // Bind the output texture of the preivous post process as the input to this post process.
  65091. var source;
  65092. if (this._shareOutputWithPostProcess) {
  65093. source = this._shareOutputWithPostProcess.inputTexture;
  65094. }
  65095. else if (this._forcedOutputTexture) {
  65096. source = this._forcedOutputTexture;
  65097. }
  65098. else {
  65099. source = this.inputTexture;
  65100. }
  65101. this._effect._bindTexture("textureSampler", source);
  65102. // Parameters
  65103. this._effect.setVector2("scale", this._scaleRatio);
  65104. this.onApplyObservable.notifyObservers(this._effect);
  65105. return this._effect;
  65106. };
  65107. PostProcess.prototype._disposeTextures = function () {
  65108. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65109. return;
  65110. }
  65111. if (this._textures.length > 0) {
  65112. for (var i = 0; i < this._textures.length; i++) {
  65113. this._engine._releaseTexture(this._textures.data[i]);
  65114. }
  65115. }
  65116. this._textures.dispose();
  65117. };
  65118. /**
  65119. * Disposes the post process.
  65120. * @param camera The camera to dispose the post process on.
  65121. */
  65122. PostProcess.prototype.dispose = function (camera) {
  65123. camera = camera || this._camera;
  65124. this._disposeTextures();
  65125. if (this._scene) {
  65126. var index_1 = this._scene.postProcesses.indexOf(this);
  65127. if (index_1 !== -1) {
  65128. this._scene.postProcesses.splice(index_1, 1);
  65129. }
  65130. }
  65131. else {
  65132. var index_2 = this._engine.postProcesses.indexOf(this);
  65133. if (index_2 !== -1) {
  65134. this._engine.postProcesses.splice(index_2, 1);
  65135. }
  65136. }
  65137. if (!camera) {
  65138. return;
  65139. }
  65140. camera.detachPostProcess(this);
  65141. var index = camera._postProcesses.indexOf(this);
  65142. if (index === 0 && camera._postProcesses.length > 0) {
  65143. var firstPostProcess = this._camera._getFirstPostProcess();
  65144. if (firstPostProcess) {
  65145. firstPostProcess.markTextureDirty();
  65146. }
  65147. }
  65148. this.onActivateObservable.clear();
  65149. this.onAfterRenderObservable.clear();
  65150. this.onApplyObservable.clear();
  65151. this.onBeforeRenderObservable.clear();
  65152. this.onSizeChangedObservable.clear();
  65153. };
  65154. return PostProcess;
  65155. }());
  65156. BABYLON.PostProcess = PostProcess;
  65157. })(BABYLON || (BABYLON = {}));
  65158. //# sourceMappingURL=babylon.postProcess.js.map
  65159. var BABYLON;
  65160. (function (BABYLON) {
  65161. var PassPostProcess = /** @class */ (function (_super) {
  65162. __extends(PassPostProcess, _super);
  65163. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65164. if (camera === void 0) { camera = null; }
  65165. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65166. if (blockCompilation === void 0) { blockCompilation = false; }
  65167. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65168. }
  65169. return PassPostProcess;
  65170. }(BABYLON.PostProcess));
  65171. BABYLON.PassPostProcess = PassPostProcess;
  65172. })(BABYLON || (BABYLON = {}));
  65173. //# sourceMappingURL=babylon.passPostProcess.js.map
  65174. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65175. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65176. s = arguments[i];
  65177. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65178. t[p] = s[p];
  65179. }
  65180. return t;
  65181. };
  65182. var BABYLON;
  65183. (function (BABYLON) {
  65184. /**
  65185. * Default implementation IShadowGenerator.
  65186. * This is the main object responsible of generating shadows in the framework.
  65187. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65188. */
  65189. var ShadowGenerator = /** @class */ (function () {
  65190. /**
  65191. * Creates a ShadowGenerator object.
  65192. * A ShadowGenerator is the required tool to use the shadows.
  65193. * Each light casting shadows needs to use its own ShadowGenerator.
  65194. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65195. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65196. * @param light The light object generating the shadows.
  65197. * @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.
  65198. */
  65199. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65200. this._bias = 0.00005;
  65201. this._normalBias = 0;
  65202. this._blurBoxOffset = 1;
  65203. this._blurScale = 2;
  65204. this._blurKernel = 1;
  65205. this._useKernelBlur = false;
  65206. this._filter = ShadowGenerator.FILTER_NONE;
  65207. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65208. this._contactHardeningLightSizeUVRatio = 0.1;
  65209. this._darkness = 0;
  65210. this._transparencyShadow = false;
  65211. /**
  65212. * Controls the extent to which the shadows fade out at the edge of the frustum
  65213. * Used only by directionals and spots
  65214. */
  65215. this.frustumEdgeFalloff = 0;
  65216. /**
  65217. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65218. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65219. * It might on the other hand introduce peter panning.
  65220. */
  65221. this.forceBackFacesOnly = false;
  65222. this._lightDirection = BABYLON.Vector3.Zero();
  65223. this._viewMatrix = BABYLON.Matrix.Zero();
  65224. this._projectionMatrix = BABYLON.Matrix.Zero();
  65225. this._transformMatrix = BABYLON.Matrix.Zero();
  65226. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65227. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65228. this._currentFaceIndex = 0;
  65229. this._currentFaceIndexCache = 0;
  65230. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65231. this._mapSize = mapSize;
  65232. this._light = light;
  65233. this._scene = light.getScene();
  65234. light._shadowGenerator = this;
  65235. // Texture type fallback from float to int if not supported.
  65236. var caps = this._scene.getEngine().getCaps();
  65237. if (!useFullFloatFirst) {
  65238. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65239. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65240. }
  65241. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65242. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65243. }
  65244. else {
  65245. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65246. }
  65247. }
  65248. else {
  65249. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65250. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65251. }
  65252. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65253. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65254. }
  65255. else {
  65256. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65257. }
  65258. }
  65259. this._initializeGenerator();
  65260. this._applyFilterValues();
  65261. }
  65262. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65263. /**
  65264. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65265. */
  65266. get: function () {
  65267. return this._bias;
  65268. },
  65269. /**
  65270. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65271. */
  65272. set: function (bias) {
  65273. this._bias = bias;
  65274. },
  65275. enumerable: true,
  65276. configurable: true
  65277. });
  65278. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65279. /**
  65280. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65281. */
  65282. get: function () {
  65283. return this._normalBias;
  65284. },
  65285. /**
  65286. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65287. */
  65288. set: function (normalBias) {
  65289. this._normalBias = normalBias;
  65290. },
  65291. enumerable: true,
  65292. configurable: true
  65293. });
  65294. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65295. /**
  65296. * Gets the blur box offset: offset applied during the blur pass.
  65297. * Only usefull if useKernelBlur = false
  65298. */
  65299. get: function () {
  65300. return this._blurBoxOffset;
  65301. },
  65302. /**
  65303. * Sets the blur box offset: offset applied during the blur pass.
  65304. * Only usefull if useKernelBlur = false
  65305. */
  65306. set: function (value) {
  65307. if (this._blurBoxOffset === value) {
  65308. return;
  65309. }
  65310. this._blurBoxOffset = value;
  65311. this._disposeBlurPostProcesses();
  65312. },
  65313. enumerable: true,
  65314. configurable: true
  65315. });
  65316. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65317. /**
  65318. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65319. * 2 means half of the size.
  65320. */
  65321. get: function () {
  65322. return this._blurScale;
  65323. },
  65324. /**
  65325. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65326. * 2 means half of the size.
  65327. */
  65328. set: function (value) {
  65329. if (this._blurScale === value) {
  65330. return;
  65331. }
  65332. this._blurScale = value;
  65333. this._disposeBlurPostProcesses();
  65334. },
  65335. enumerable: true,
  65336. configurable: true
  65337. });
  65338. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65339. /**
  65340. * Gets the blur kernel: kernel size of the blur pass.
  65341. * Only usefull if useKernelBlur = true
  65342. */
  65343. get: function () {
  65344. return this._blurKernel;
  65345. },
  65346. /**
  65347. * Sets the blur kernel: kernel size of the blur pass.
  65348. * Only usefull if useKernelBlur = true
  65349. */
  65350. set: function (value) {
  65351. if (this._blurKernel === value) {
  65352. return;
  65353. }
  65354. this._blurKernel = value;
  65355. this._disposeBlurPostProcesses();
  65356. },
  65357. enumerable: true,
  65358. configurable: true
  65359. });
  65360. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65361. /**
  65362. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65363. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65364. */
  65365. get: function () {
  65366. return this._useKernelBlur;
  65367. },
  65368. /**
  65369. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65370. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65371. */
  65372. set: function (value) {
  65373. if (this._useKernelBlur === value) {
  65374. return;
  65375. }
  65376. this._useKernelBlur = value;
  65377. this._disposeBlurPostProcesses();
  65378. },
  65379. enumerable: true,
  65380. configurable: true
  65381. });
  65382. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65383. /**
  65384. * Gets the depth scale used in ESM mode.
  65385. */
  65386. get: function () {
  65387. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65388. },
  65389. /**
  65390. * Sets the depth scale used in ESM mode.
  65391. * This can override the scale stored on the light.
  65392. */
  65393. set: function (value) {
  65394. this._depthScale = value;
  65395. },
  65396. enumerable: true,
  65397. configurable: true
  65398. });
  65399. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65400. /**
  65401. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65402. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65403. */
  65404. get: function () {
  65405. return this._filter;
  65406. },
  65407. /**
  65408. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65409. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65410. */
  65411. set: function (value) {
  65412. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65413. if (this._light.needCube()) {
  65414. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65415. this.useExponentialShadowMap = true;
  65416. return;
  65417. }
  65418. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65419. this.useCloseExponentialShadowMap = true;
  65420. return;
  65421. }
  65422. // PCF on cubemap would also be expensive
  65423. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65424. this.usePoissonSampling = true;
  65425. return;
  65426. }
  65427. }
  65428. // Weblg1 fallback for PCF.
  65429. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65430. if (this._scene.getEngine().webGLVersion === 1) {
  65431. this.usePoissonSampling = true;
  65432. return;
  65433. }
  65434. }
  65435. if (this._filter === value) {
  65436. return;
  65437. }
  65438. this._filter = value;
  65439. this._disposeBlurPostProcesses();
  65440. this._applyFilterValues();
  65441. this._light._markMeshesAsLightDirty();
  65442. },
  65443. enumerable: true,
  65444. configurable: true
  65445. });
  65446. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65447. /**
  65448. * Gets if the current filter is set to Poisson Sampling.
  65449. */
  65450. get: function () {
  65451. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65452. },
  65453. /**
  65454. * Sets the current filter to Poisson Sampling.
  65455. */
  65456. set: function (value) {
  65457. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65458. return;
  65459. }
  65460. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65461. },
  65462. enumerable: true,
  65463. configurable: true
  65464. });
  65465. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65466. /**
  65467. * Gets if the current filter is set to VSM.
  65468. * DEPRECATED. Should use useExponentialShadowMap instead.
  65469. */
  65470. get: function () {
  65471. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65472. return this.useExponentialShadowMap;
  65473. },
  65474. /**
  65475. * Sets the current filter is to VSM.
  65476. * DEPRECATED. Should use useExponentialShadowMap instead.
  65477. */
  65478. set: function (value) {
  65479. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65480. this.useExponentialShadowMap = value;
  65481. },
  65482. enumerable: true,
  65483. configurable: true
  65484. });
  65485. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65486. /**
  65487. * Gets if the current filter is set to blurred VSM.
  65488. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65489. */
  65490. get: function () {
  65491. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65492. return this.useBlurExponentialShadowMap;
  65493. },
  65494. /**
  65495. * Sets the current filter is to blurred VSM.
  65496. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65497. */
  65498. set: function (value) {
  65499. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65500. this.useBlurExponentialShadowMap = value;
  65501. },
  65502. enumerable: true,
  65503. configurable: true
  65504. });
  65505. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65506. /**
  65507. * Gets if the current filter is set to ESM.
  65508. */
  65509. get: function () {
  65510. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65511. },
  65512. /**
  65513. * Sets the current filter is to ESM.
  65514. */
  65515. set: function (value) {
  65516. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65517. return;
  65518. }
  65519. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65520. },
  65521. enumerable: true,
  65522. configurable: true
  65523. });
  65524. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65525. /**
  65526. * Gets if the current filter is set to filtered ESM.
  65527. */
  65528. get: function () {
  65529. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65530. },
  65531. /**
  65532. * Gets if the current filter is set to filtered ESM.
  65533. */
  65534. set: function (value) {
  65535. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65536. return;
  65537. }
  65538. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65539. },
  65540. enumerable: true,
  65541. configurable: true
  65542. });
  65543. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65544. /**
  65545. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65546. * exponential to prevent steep falloff artifacts).
  65547. */
  65548. get: function () {
  65549. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65550. },
  65551. /**
  65552. * Sets the current filter to "close ESM" (using the inverse of the
  65553. * exponential to prevent steep falloff artifacts).
  65554. */
  65555. set: function (value) {
  65556. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65557. return;
  65558. }
  65559. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65560. },
  65561. enumerable: true,
  65562. configurable: true
  65563. });
  65564. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65565. /**
  65566. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65567. * exponential to prevent steep falloff artifacts).
  65568. */
  65569. get: function () {
  65570. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65571. },
  65572. /**
  65573. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65574. * exponential to prevent steep falloff artifacts).
  65575. */
  65576. set: function (value) {
  65577. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65578. return;
  65579. }
  65580. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65581. },
  65582. enumerable: true,
  65583. configurable: true
  65584. });
  65585. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65586. /**
  65587. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65588. */
  65589. get: function () {
  65590. return this.filter === ShadowGenerator.FILTER_PCF;
  65591. },
  65592. /**
  65593. * Sets the current filter to "PCF" (percentage closer filtering).
  65594. */
  65595. set: function (value) {
  65596. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65597. return;
  65598. }
  65599. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65600. },
  65601. enumerable: true,
  65602. configurable: true
  65603. });
  65604. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65605. /**
  65606. * Gets the PCF or PCSS Quality.
  65607. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65608. */
  65609. get: function () {
  65610. return this._filteringQuality;
  65611. },
  65612. /**
  65613. * Sets the PCF or PCSS Quality.
  65614. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65615. */
  65616. set: function (filteringQuality) {
  65617. this._filteringQuality = filteringQuality;
  65618. },
  65619. enumerable: true,
  65620. configurable: true
  65621. });
  65622. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65623. /**
  65624. * Gets if the current filter is set to "PCSS" (contact hardening).
  65625. */
  65626. get: function () {
  65627. return this.filter === ShadowGenerator.FILTER_PCSS;
  65628. },
  65629. /**
  65630. * Sets the current filter to "PCSS" (contact hardening).
  65631. */
  65632. set: function (value) {
  65633. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65634. return;
  65635. }
  65636. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65637. },
  65638. enumerable: true,
  65639. configurable: true
  65640. });
  65641. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65642. /**
  65643. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65644. * Using a ratio helps keeping shape stability independently of the map size.
  65645. *
  65646. * It does not account for the light projection as it was having too much
  65647. * instability during the light setup or during light position changes.
  65648. *
  65649. * Only valid if useContactHardeningShadow is true.
  65650. */
  65651. get: function () {
  65652. return this._contactHardeningLightSizeUVRatio;
  65653. },
  65654. /**
  65655. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65656. * Using a ratio helps keeping shape stability independently of the map size.
  65657. *
  65658. * It does not account for the light projection as it was having too much
  65659. * instability during the light setup or during light position changes.
  65660. *
  65661. * Only valid if useContactHardeningShadow is true.
  65662. */
  65663. set: function (contactHardeningLightSizeUVRatio) {
  65664. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65665. },
  65666. enumerable: true,
  65667. configurable: true
  65668. });
  65669. /**
  65670. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65671. * 0 means strongest and 1 would means no shadow.
  65672. * @returns the darkness.
  65673. */
  65674. ShadowGenerator.prototype.getDarkness = function () {
  65675. return this._darkness;
  65676. };
  65677. /**
  65678. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65679. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65680. * @returns the shadow generator allowing fluent coding.
  65681. */
  65682. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65683. if (darkness >= 1.0)
  65684. this._darkness = 1.0;
  65685. else if (darkness <= 0.0)
  65686. this._darkness = 0.0;
  65687. else
  65688. this._darkness = darkness;
  65689. return this;
  65690. };
  65691. /**
  65692. * Sets the ability to have transparent shadow (boolean).
  65693. * @param transparent True if transparent else False
  65694. * @returns the shadow generator allowing fluent coding
  65695. */
  65696. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65697. this._transparencyShadow = transparent;
  65698. return this;
  65699. };
  65700. /**
  65701. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65702. * @returns The render target texture if present otherwise, null
  65703. */
  65704. ShadowGenerator.prototype.getShadowMap = function () {
  65705. return this._shadowMap;
  65706. };
  65707. /**
  65708. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65709. * @returns The render target texture if the shadow map is present otherwise, null
  65710. */
  65711. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65712. if (this._shadowMap2) {
  65713. return this._shadowMap2;
  65714. }
  65715. return this._shadowMap;
  65716. };
  65717. /**
  65718. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65719. * @param mesh Mesh to add
  65720. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65721. * @returns the Shadow Generator itself
  65722. */
  65723. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65724. if (includeDescendants === void 0) { includeDescendants = true; }
  65725. if (!this._shadowMap) {
  65726. return this;
  65727. }
  65728. if (!this._shadowMap.renderList) {
  65729. this._shadowMap.renderList = [];
  65730. }
  65731. this._shadowMap.renderList.push(mesh);
  65732. if (includeDescendants) {
  65733. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65734. }
  65735. return this;
  65736. var _a;
  65737. };
  65738. /**
  65739. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65740. * @param mesh Mesh to remove
  65741. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65742. * @returns the Shadow Generator itself
  65743. */
  65744. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65745. if (includeDescendants === void 0) { includeDescendants = true; }
  65746. if (!this._shadowMap || !this._shadowMap.renderList) {
  65747. return this;
  65748. }
  65749. var index = this._shadowMap.renderList.indexOf(mesh);
  65750. if (index !== -1) {
  65751. this._shadowMap.renderList.splice(index, 1);
  65752. }
  65753. if (includeDescendants) {
  65754. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65755. var child = _a[_i];
  65756. this.removeShadowCaster(child);
  65757. }
  65758. }
  65759. return this;
  65760. };
  65761. /**
  65762. * Returns the associated light object.
  65763. * @returns the light generating the shadow
  65764. */
  65765. ShadowGenerator.prototype.getLight = function () {
  65766. return this._light;
  65767. };
  65768. ShadowGenerator.prototype._initializeGenerator = function () {
  65769. this._light._markMeshesAsLightDirty();
  65770. this._initializeShadowMap();
  65771. };
  65772. ShadowGenerator.prototype._initializeShadowMap = function () {
  65773. var _this = this;
  65774. // Render target
  65775. var engine = this._scene.getEngine();
  65776. if (engine.webGLVersion > 1) {
  65777. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65778. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65779. }
  65780. else {
  65781. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65782. }
  65783. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65784. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65785. this._shadowMap.anisotropicFilteringLevel = 1;
  65786. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65787. this._shadowMap.renderParticles = false;
  65788. this._shadowMap.ignoreCameraViewport = true;
  65789. // Record Face Index before render.
  65790. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65791. _this._currentFaceIndex = faceIndex;
  65792. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65793. engine.setColorWrite(false);
  65794. }
  65795. });
  65796. // Custom render function.
  65797. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65798. // Blur if required afer render.
  65799. this._shadowMap.onAfterUnbindObservable.add(function () {
  65800. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65801. engine.setColorWrite(true);
  65802. }
  65803. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65804. return;
  65805. }
  65806. var shadowMap = _this.getShadowMapForRendering();
  65807. if (shadowMap) {
  65808. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65809. }
  65810. });
  65811. // Clear according to the chosen filter.
  65812. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65813. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65814. this._shadowMap.onClearObservable.add(function (engine) {
  65815. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65816. engine.clear(clearOne, false, true, false);
  65817. }
  65818. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65819. engine.clear(clearZero, true, true, false);
  65820. }
  65821. else {
  65822. engine.clear(clearOne, true, true, false);
  65823. }
  65824. });
  65825. };
  65826. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65827. var _this = this;
  65828. var engine = this._scene.getEngine();
  65829. var targetSize = this._mapSize / this.blurScale;
  65830. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65831. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65832. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65833. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65834. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65835. }
  65836. if (this.useKernelBlur) {
  65837. 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);
  65838. this._kernelBlurXPostprocess.width = targetSize;
  65839. this._kernelBlurXPostprocess.height = targetSize;
  65840. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65841. effect.setTexture("textureSampler", _this._shadowMap);
  65842. });
  65843. 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);
  65844. this._kernelBlurXPostprocess.autoClear = false;
  65845. this._kernelBlurYPostprocess.autoClear = false;
  65846. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65847. this._kernelBlurXPostprocess.packedFloat = true;
  65848. this._kernelBlurYPostprocess.packedFloat = true;
  65849. }
  65850. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65851. }
  65852. else {
  65853. 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);
  65854. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65855. effect.setFloat2("screenSize", targetSize, targetSize);
  65856. effect.setTexture("textureSampler", _this._shadowMap);
  65857. });
  65858. this._boxBlurPostprocess.autoClear = false;
  65859. this._blurPostProcesses = [this._boxBlurPostprocess];
  65860. }
  65861. };
  65862. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65863. var index;
  65864. var engine = this._scene.getEngine();
  65865. if (depthOnlySubMeshes.length) {
  65866. engine.setColorWrite(false);
  65867. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65868. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65869. }
  65870. engine.setColorWrite(true);
  65871. }
  65872. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65873. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65874. }
  65875. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65876. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65877. }
  65878. if (this._transparencyShadow) {
  65879. for (index = 0; index < transparentSubMeshes.length; index++) {
  65880. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65881. }
  65882. }
  65883. };
  65884. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65885. var _this = this;
  65886. var mesh = subMesh.getRenderingMesh();
  65887. var scene = this._scene;
  65888. var engine = scene.getEngine();
  65889. var material = subMesh.getMaterial();
  65890. if (!material) {
  65891. return;
  65892. }
  65893. // Culling
  65894. engine.setState(material.backFaceCulling);
  65895. // Managing instances
  65896. var batch = mesh._getInstancesRenderList(subMesh._id);
  65897. if (batch.mustReturn) {
  65898. return;
  65899. }
  65900. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65901. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65902. engine.enableEffect(this._effect);
  65903. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65904. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65905. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65906. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65907. this._effect.setVector3("lightData", this._cachedDirection);
  65908. }
  65909. else {
  65910. this._effect.setVector3("lightData", this._cachedPosition);
  65911. }
  65912. if (scene.activeCamera) {
  65913. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65914. }
  65915. // Alpha test
  65916. if (material && material.needAlphaTesting()) {
  65917. var alphaTexture = material.getAlphaTestTexture();
  65918. if (alphaTexture) {
  65919. this._effect.setTexture("diffuseSampler", alphaTexture);
  65920. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65921. }
  65922. }
  65923. // Bones
  65924. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65925. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65926. }
  65927. // Morph targets
  65928. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65929. if (this.forceBackFacesOnly) {
  65930. engine.setState(true, 0, false, true);
  65931. }
  65932. // Draw
  65933. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65934. if (this.forceBackFacesOnly) {
  65935. engine.setState(true, 0, false, false);
  65936. }
  65937. }
  65938. else {
  65939. // Need to reset refresh rate of the shadowMap
  65940. if (this._shadowMap) {
  65941. this._shadowMap.resetRefreshCounter();
  65942. }
  65943. }
  65944. };
  65945. ShadowGenerator.prototype._applyFilterValues = function () {
  65946. if (!this._shadowMap) {
  65947. return;
  65948. }
  65949. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65950. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65951. }
  65952. else {
  65953. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65954. }
  65955. };
  65956. /**
  65957. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65958. * @param onCompiled Callback triggered at the and of the effects compilation
  65959. * @param options Sets of optional options forcing the compilation with different modes
  65960. */
  65961. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65962. var _this = this;
  65963. var localOptions = __assign({ useInstances: false }, options);
  65964. var shadowMap = this.getShadowMap();
  65965. if (!shadowMap) {
  65966. if (onCompiled) {
  65967. onCompiled(this);
  65968. }
  65969. return;
  65970. }
  65971. var renderList = shadowMap.renderList;
  65972. if (!renderList) {
  65973. if (onCompiled) {
  65974. onCompiled(this);
  65975. }
  65976. return;
  65977. }
  65978. var subMeshes = new Array();
  65979. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65980. var mesh = renderList_1[_i];
  65981. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65982. }
  65983. if (subMeshes.length === 0) {
  65984. if (onCompiled) {
  65985. onCompiled(this);
  65986. }
  65987. return;
  65988. }
  65989. var currentIndex = 0;
  65990. var checkReady = function () {
  65991. if (!_this._scene || !_this._scene.getEngine()) {
  65992. return;
  65993. }
  65994. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65995. currentIndex++;
  65996. if (currentIndex >= subMeshes.length) {
  65997. if (onCompiled) {
  65998. onCompiled(_this);
  65999. }
  66000. return;
  66001. }
  66002. }
  66003. setTimeout(checkReady, 16);
  66004. };
  66005. checkReady();
  66006. };
  66007. /**
  66008. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66009. * @param options Sets of optional options forcing the compilation with different modes
  66010. * @returns A promise that resolves when the compilation completes
  66011. */
  66012. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66013. var _this = this;
  66014. return new Promise(function (resolve) {
  66015. _this.forceCompilation(function () {
  66016. resolve();
  66017. }, options);
  66018. });
  66019. };
  66020. /**
  66021. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66022. * @param subMesh The submesh we want to render in the shadow map
  66023. * @param useInstances Defines wether will draw in the map using instances
  66024. * @returns true if ready otherwise, false
  66025. */
  66026. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66027. var defines = [];
  66028. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66029. defines.push("#define FLOAT");
  66030. }
  66031. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66032. defines.push("#define ESM");
  66033. }
  66034. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66035. defines.push("#define DEPTHTEXTURE");
  66036. }
  66037. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66038. var mesh = subMesh.getMesh();
  66039. var material = subMesh.getMaterial();
  66040. // Normal bias.
  66041. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66042. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66043. defines.push("#define NORMAL");
  66044. if (mesh.nonUniformScaling) {
  66045. defines.push("#define NONUNIFORMSCALING");
  66046. }
  66047. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66048. defines.push("#define DIRECTIONINLIGHTDATA");
  66049. }
  66050. }
  66051. // Alpha test
  66052. if (material && material.needAlphaTesting()) {
  66053. var alphaTexture = material.getAlphaTestTexture();
  66054. if (alphaTexture) {
  66055. defines.push("#define ALPHATEST");
  66056. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66057. attribs.push(BABYLON.VertexBuffer.UVKind);
  66058. defines.push("#define UV1");
  66059. }
  66060. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66061. if (alphaTexture.coordinatesIndex === 1) {
  66062. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66063. defines.push("#define UV2");
  66064. }
  66065. }
  66066. }
  66067. }
  66068. // Bones
  66069. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66070. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66071. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66072. if (mesh.numBoneInfluencers > 4) {
  66073. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66074. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66075. }
  66076. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66077. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66078. }
  66079. else {
  66080. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66081. }
  66082. // Morph targets
  66083. var manager = mesh.morphTargetManager;
  66084. var morphInfluencers = 0;
  66085. if (manager) {
  66086. if (manager.numInfluencers > 0) {
  66087. defines.push("#define MORPHTARGETS");
  66088. morphInfluencers = manager.numInfluencers;
  66089. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66090. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66091. }
  66092. }
  66093. // Instances
  66094. if (useInstances) {
  66095. defines.push("#define INSTANCES");
  66096. attribs.push("world0");
  66097. attribs.push("world1");
  66098. attribs.push("world2");
  66099. attribs.push("world3");
  66100. }
  66101. // Get correct effect
  66102. var join = defines.join("\n");
  66103. if (this._cachedDefines !== join) {
  66104. this._cachedDefines = join;
  66105. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66106. }
  66107. if (!this._effect.isReady()) {
  66108. return false;
  66109. }
  66110. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66111. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66112. this._initializeBlurRTTAndPostProcesses();
  66113. }
  66114. }
  66115. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66116. return false;
  66117. }
  66118. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66119. return false;
  66120. }
  66121. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66122. return false;
  66123. }
  66124. return true;
  66125. };
  66126. /**
  66127. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66128. * @param defines Defines of the material we want to update
  66129. * @param lightIndex Index of the light in the enabled light list of the material
  66130. */
  66131. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66132. var scene = this._scene;
  66133. var light = this._light;
  66134. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66135. return;
  66136. }
  66137. defines["SHADOW" + lightIndex] = true;
  66138. if (this.useContactHardeningShadow) {
  66139. defines["SHADOWPCSS" + lightIndex] = true;
  66140. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66141. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66142. }
  66143. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66144. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66145. }
  66146. // else default to high.
  66147. }
  66148. if (this.usePercentageCloserFiltering) {
  66149. defines["SHADOWPCF" + lightIndex] = true;
  66150. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66151. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66152. }
  66153. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66154. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66155. }
  66156. // else default to high.
  66157. }
  66158. else if (this.usePoissonSampling) {
  66159. defines["SHADOWPOISSON" + lightIndex] = true;
  66160. }
  66161. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66162. defines["SHADOWESM" + lightIndex] = true;
  66163. }
  66164. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66165. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66166. }
  66167. if (light.needCube()) {
  66168. defines["SHADOWCUBE" + lightIndex] = true;
  66169. }
  66170. };
  66171. /**
  66172. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66173. * defined in the generator but impacting the effect).
  66174. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66175. * @param effect The effect we are binfing the information for
  66176. */
  66177. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66178. var light = this._light;
  66179. var scene = this._scene;
  66180. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66181. return;
  66182. }
  66183. var camera = scene.activeCamera;
  66184. if (!camera) {
  66185. return;
  66186. }
  66187. var shadowMap = this.getShadowMap();
  66188. if (!shadowMap) {
  66189. return;
  66190. }
  66191. if (!light.needCube()) {
  66192. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66193. }
  66194. // Only PCF uses depth stencil texture.
  66195. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66196. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66197. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66198. }
  66199. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66200. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66201. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66202. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66203. }
  66204. else {
  66205. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66206. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66207. }
  66208. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66209. };
  66210. /**
  66211. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66212. * (eq to shadow prjection matrix * light transform matrix)
  66213. * @returns The transform matrix used to create the shadow map
  66214. */
  66215. ShadowGenerator.prototype.getTransformMatrix = function () {
  66216. var scene = this._scene;
  66217. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66218. return this._transformMatrix;
  66219. }
  66220. this._currentRenderID = scene.getRenderId();
  66221. this._currentFaceIndexCache = this._currentFaceIndex;
  66222. var lightPosition = this._light.position;
  66223. if (this._light.computeTransformedInformation()) {
  66224. lightPosition = this._light.transformedPosition;
  66225. }
  66226. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66227. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66228. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66229. }
  66230. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66231. this._cachedPosition.copyFrom(lightPosition);
  66232. this._cachedDirection.copyFrom(this._lightDirection);
  66233. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66234. var shadowMap = this.getShadowMap();
  66235. if (shadowMap) {
  66236. var renderList = shadowMap.renderList;
  66237. if (renderList) {
  66238. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66239. }
  66240. }
  66241. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66242. }
  66243. return this._transformMatrix;
  66244. };
  66245. /**
  66246. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66247. * Cube and 2D textures for instance.
  66248. */
  66249. ShadowGenerator.prototype.recreateShadowMap = function () {
  66250. var shadowMap = this._shadowMap;
  66251. if (!shadowMap) {
  66252. return;
  66253. }
  66254. // Track render list.
  66255. var renderList = shadowMap.renderList;
  66256. // Clean up existing data.
  66257. this._disposeRTTandPostProcesses();
  66258. // Reinitializes.
  66259. this._initializeGenerator();
  66260. // Reaffect the filter to ensure a correct fallback if necessary.
  66261. this.filter = this.filter;
  66262. // Reaffect the filter.
  66263. this._applyFilterValues();
  66264. // Reaffect Render List.
  66265. this._shadowMap.renderList = renderList;
  66266. };
  66267. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66268. if (this._shadowMap2) {
  66269. this._shadowMap2.dispose();
  66270. this._shadowMap2 = null;
  66271. }
  66272. if (this._boxBlurPostprocess) {
  66273. this._boxBlurPostprocess.dispose();
  66274. this._boxBlurPostprocess = null;
  66275. }
  66276. if (this._kernelBlurXPostprocess) {
  66277. this._kernelBlurXPostprocess.dispose();
  66278. this._kernelBlurXPostprocess = null;
  66279. }
  66280. if (this._kernelBlurYPostprocess) {
  66281. this._kernelBlurYPostprocess.dispose();
  66282. this._kernelBlurYPostprocess = null;
  66283. }
  66284. this._blurPostProcesses = [];
  66285. };
  66286. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66287. if (this._shadowMap) {
  66288. this._shadowMap.dispose();
  66289. this._shadowMap = null;
  66290. }
  66291. this._disposeBlurPostProcesses();
  66292. };
  66293. /**
  66294. * Disposes the ShadowGenerator.
  66295. * Returns nothing.
  66296. */
  66297. ShadowGenerator.prototype.dispose = function () {
  66298. this._disposeRTTandPostProcesses();
  66299. if (this._light) {
  66300. this._light._shadowGenerator = null;
  66301. this._light._markMeshesAsLightDirty();
  66302. }
  66303. };
  66304. /**
  66305. * Serializes the shadow generator setup to a json object.
  66306. * @returns The serialized JSON object
  66307. */
  66308. ShadowGenerator.prototype.serialize = function () {
  66309. var serializationObject = {};
  66310. var shadowMap = this.getShadowMap();
  66311. if (!shadowMap) {
  66312. return serializationObject;
  66313. }
  66314. serializationObject.lightId = this._light.id;
  66315. serializationObject.mapSize = shadowMap.getRenderSize();
  66316. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66317. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66318. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66319. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66320. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66321. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66322. serializationObject.depthScale = this.depthScale;
  66323. serializationObject.darkness = this.getDarkness();
  66324. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66325. serializationObject.blurKernel = this.blurKernel;
  66326. serializationObject.blurScale = this.blurScale;
  66327. serializationObject.useKernelBlur = this.useKernelBlur;
  66328. serializationObject.transparencyShadow = this._transparencyShadow;
  66329. serializationObject.bias = this.bias;
  66330. serializationObject.normalBias = this.normalBias;
  66331. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66332. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66333. serializationObject.filteringQuality = this.filteringQuality;
  66334. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66335. serializationObject.renderList = [];
  66336. if (shadowMap.renderList) {
  66337. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66338. var mesh = shadowMap.renderList[meshIndex];
  66339. serializationObject.renderList.push(mesh.id);
  66340. }
  66341. }
  66342. return serializationObject;
  66343. };
  66344. /**
  66345. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66346. * @param parsedShadowGenerator The JSON object to parse
  66347. * @param scene The scene to create the shadow map for
  66348. * @returns The parsed shadow generator
  66349. */
  66350. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66351. //casting to point light, as light is missing the position attr and typescript complains.
  66352. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66353. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66354. var shadowMap = shadowGenerator.getShadowMap();
  66355. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66356. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66357. meshes.forEach(function (mesh) {
  66358. if (!shadowMap) {
  66359. return;
  66360. }
  66361. if (!shadowMap.renderList) {
  66362. shadowMap.renderList = [];
  66363. }
  66364. shadowMap.renderList.push(mesh);
  66365. });
  66366. }
  66367. if (parsedShadowGenerator.usePoissonSampling) {
  66368. shadowGenerator.usePoissonSampling = true;
  66369. }
  66370. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66371. shadowGenerator.useExponentialShadowMap = true;
  66372. }
  66373. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66374. shadowGenerator.useBlurExponentialShadowMap = true;
  66375. }
  66376. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66377. shadowGenerator.useCloseExponentialShadowMap = true;
  66378. }
  66379. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66380. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66381. }
  66382. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66383. shadowGenerator.usePercentageCloserFiltering = true;
  66384. }
  66385. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66386. shadowGenerator.useContactHardeningShadow = true;
  66387. }
  66388. if (parsedShadowGenerator.filteringQuality) {
  66389. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66390. }
  66391. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66392. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66393. }
  66394. // Backward compat
  66395. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66396. shadowGenerator.useExponentialShadowMap = true;
  66397. }
  66398. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66399. shadowGenerator.useBlurExponentialShadowMap = true;
  66400. }
  66401. if (parsedShadowGenerator.depthScale) {
  66402. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66403. }
  66404. if (parsedShadowGenerator.blurScale) {
  66405. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66406. }
  66407. if (parsedShadowGenerator.blurBoxOffset) {
  66408. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66409. }
  66410. if (parsedShadowGenerator.useKernelBlur) {
  66411. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66412. }
  66413. if (parsedShadowGenerator.blurKernel) {
  66414. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66415. }
  66416. if (parsedShadowGenerator.bias !== undefined) {
  66417. shadowGenerator.bias = parsedShadowGenerator.bias;
  66418. }
  66419. if (parsedShadowGenerator.normalBias !== undefined) {
  66420. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66421. }
  66422. if (parsedShadowGenerator.darkness) {
  66423. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66424. }
  66425. if (parsedShadowGenerator.transparencyShadow) {
  66426. shadowGenerator.setTransparencyShadow(true);
  66427. }
  66428. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66429. return shadowGenerator;
  66430. };
  66431. /**
  66432. * Shadow generator mode None: no filtering applied.
  66433. */
  66434. ShadowGenerator.FILTER_NONE = 0;
  66435. /**
  66436. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66437. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66438. */
  66439. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66440. /**
  66441. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66442. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66443. */
  66444. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66445. /**
  66446. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66447. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66448. */
  66449. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66450. /**
  66451. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66452. * edge artifacts on steep falloff.
  66453. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66454. */
  66455. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66456. /**
  66457. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66458. * edge artifacts on steep falloff.
  66459. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66460. */
  66461. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66462. /**
  66463. * Shadow generator mode PCF: Percentage Closer Filtering
  66464. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66465. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66466. */
  66467. ShadowGenerator.FILTER_PCF = 6;
  66468. /**
  66469. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66470. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66471. * Contact Hardening
  66472. */
  66473. ShadowGenerator.FILTER_PCSS = 7;
  66474. /**
  66475. * Reserved for PCF and PCSS
  66476. * Highest Quality.
  66477. *
  66478. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66479. *
  66480. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66481. */
  66482. ShadowGenerator.QUALITY_HIGH = 0;
  66483. /**
  66484. * Reserved for PCF and PCSS
  66485. * Good tradeoff for quality/perf cross devices
  66486. *
  66487. * Execute PCF on a 3*3 kernel.
  66488. *
  66489. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66490. */
  66491. ShadowGenerator.QUALITY_MEDIUM = 1;
  66492. /**
  66493. * Reserved for PCF and PCSS
  66494. * The lowest quality but the fastest.
  66495. *
  66496. * Execute PCF on a 1*1 kernel.
  66497. *
  66498. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66499. */
  66500. ShadowGenerator.QUALITY_LOW = 2;
  66501. return ShadowGenerator;
  66502. }());
  66503. BABYLON.ShadowGenerator = ShadowGenerator;
  66504. })(BABYLON || (BABYLON = {}));
  66505. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66506. var BABYLON;
  66507. (function (BABYLON) {
  66508. var DefaultLoadingScreen = /** @class */ (function () {
  66509. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66510. if (_loadingText === void 0) { _loadingText = ""; }
  66511. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66512. var _this = this;
  66513. this._renderingCanvas = _renderingCanvas;
  66514. this._loadingText = _loadingText;
  66515. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66516. // Resize
  66517. this._resizeLoadingUI = function () {
  66518. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66519. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66520. if (!_this._loadingDiv) {
  66521. return;
  66522. }
  66523. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66524. _this._loadingDiv.style.left = canvasRect.left + "px";
  66525. _this._loadingDiv.style.top = canvasRect.top + "px";
  66526. _this._loadingDiv.style.width = canvasRect.width + "px";
  66527. _this._loadingDiv.style.height = canvasRect.height + "px";
  66528. };
  66529. }
  66530. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66531. if (this._loadingDiv) {
  66532. // Do not add a loading screen if there is already one
  66533. return;
  66534. }
  66535. this._loadingDiv = document.createElement("div");
  66536. this._loadingDiv.id = "babylonjsLoadingDiv";
  66537. this._loadingDiv.style.opacity = "0";
  66538. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66539. this._loadingDiv.style.pointerEvents = "none";
  66540. // Loading text
  66541. this._loadingTextDiv = document.createElement("div");
  66542. this._loadingTextDiv.style.position = "absolute";
  66543. this._loadingTextDiv.style.left = "0";
  66544. this._loadingTextDiv.style.top = "50%";
  66545. this._loadingTextDiv.style.marginTop = "80px";
  66546. this._loadingTextDiv.style.width = "100%";
  66547. this._loadingTextDiv.style.height = "20px";
  66548. this._loadingTextDiv.style.fontFamily = "Arial";
  66549. this._loadingTextDiv.style.fontSize = "14px";
  66550. this._loadingTextDiv.style.color = "white";
  66551. this._loadingTextDiv.style.textAlign = "center";
  66552. this._loadingTextDiv.innerHTML = "Loading";
  66553. this._loadingDiv.appendChild(this._loadingTextDiv);
  66554. //set the predefined text
  66555. this._loadingTextDiv.innerHTML = this._loadingText;
  66556. // Generating keyframes
  66557. var style = document.createElement('style');
  66558. style.type = 'text/css';
  66559. 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 }";
  66560. style.innerHTML = keyFrames;
  66561. document.getElementsByTagName('head')[0].appendChild(style);
  66562. // Loading img
  66563. var imgBack = new Image();
  66564. 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";
  66565. imgBack.style.position = "absolute";
  66566. imgBack.style.left = "50%";
  66567. imgBack.style.top = "50%";
  66568. imgBack.style.marginLeft = "-60px";
  66569. imgBack.style.marginTop = "-60px";
  66570. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66571. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66572. imgBack.style.transformOrigin = "50% 50%";
  66573. imgBack.style.webkitTransformOrigin = "50% 50%";
  66574. this._loadingDiv.appendChild(imgBack);
  66575. this._resizeLoadingUI();
  66576. window.addEventListener("resize", this._resizeLoadingUI);
  66577. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66578. document.body.appendChild(this._loadingDiv);
  66579. this._loadingDiv.style.opacity = "1";
  66580. };
  66581. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66582. var _this = this;
  66583. if (!this._loadingDiv) {
  66584. return;
  66585. }
  66586. var onTransitionEnd = function () {
  66587. if (!_this._loadingDiv) {
  66588. return;
  66589. }
  66590. document.body.removeChild(_this._loadingDiv);
  66591. window.removeEventListener("resize", _this._resizeLoadingUI);
  66592. _this._loadingDiv = null;
  66593. };
  66594. this._loadingDiv.style.opacity = "0";
  66595. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66596. };
  66597. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66598. set: function (text) {
  66599. this._loadingText = text;
  66600. if (this._loadingTextDiv) {
  66601. this._loadingTextDiv.innerHTML = this._loadingText;
  66602. }
  66603. },
  66604. enumerable: true,
  66605. configurable: true
  66606. });
  66607. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66608. get: function () {
  66609. return this._loadingDivBackgroundColor;
  66610. },
  66611. set: function (color) {
  66612. this._loadingDivBackgroundColor = color;
  66613. if (!this._loadingDiv) {
  66614. return;
  66615. }
  66616. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66617. },
  66618. enumerable: true,
  66619. configurable: true
  66620. });
  66621. return DefaultLoadingScreen;
  66622. }());
  66623. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66624. })(BABYLON || (BABYLON = {}));
  66625. //# sourceMappingURL=babylon.loadingScreen.js.map
  66626. var BABYLON;
  66627. (function (BABYLON) {
  66628. var SceneLoaderProgressEvent = /** @class */ (function () {
  66629. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66630. this.lengthComputable = lengthComputable;
  66631. this.loaded = loaded;
  66632. this.total = total;
  66633. }
  66634. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66635. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66636. };
  66637. return SceneLoaderProgressEvent;
  66638. }());
  66639. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66640. var SceneLoader = /** @class */ (function () {
  66641. function SceneLoader() {
  66642. }
  66643. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66644. get: function () {
  66645. return 0;
  66646. },
  66647. enumerable: true,
  66648. configurable: true
  66649. });
  66650. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66651. get: function () {
  66652. return 1;
  66653. },
  66654. enumerable: true,
  66655. configurable: true
  66656. });
  66657. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66658. get: function () {
  66659. return 2;
  66660. },
  66661. enumerable: true,
  66662. configurable: true
  66663. });
  66664. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66665. get: function () {
  66666. return 3;
  66667. },
  66668. enumerable: true,
  66669. configurable: true
  66670. });
  66671. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66672. get: function () {
  66673. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66674. },
  66675. set: function (value) {
  66676. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66677. },
  66678. enumerable: true,
  66679. configurable: true
  66680. });
  66681. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66682. get: function () {
  66683. return SceneLoader._ShowLoadingScreen;
  66684. },
  66685. set: function (value) {
  66686. SceneLoader._ShowLoadingScreen = value;
  66687. },
  66688. enumerable: true,
  66689. configurable: true
  66690. });
  66691. Object.defineProperty(SceneLoader, "loggingLevel", {
  66692. get: function () {
  66693. return SceneLoader._loggingLevel;
  66694. },
  66695. set: function (value) {
  66696. SceneLoader._loggingLevel = value;
  66697. },
  66698. enumerable: true,
  66699. configurable: true
  66700. });
  66701. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66702. get: function () {
  66703. return SceneLoader._CleanBoneMatrixWeights;
  66704. },
  66705. set: function (value) {
  66706. SceneLoader._CleanBoneMatrixWeights = value;
  66707. },
  66708. enumerable: true,
  66709. configurable: true
  66710. });
  66711. SceneLoader._getDefaultPlugin = function () {
  66712. return SceneLoader._registeredPlugins[".babylon"];
  66713. };
  66714. SceneLoader._getPluginForExtension = function (extension) {
  66715. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66716. if (registeredPlugin) {
  66717. return registeredPlugin;
  66718. }
  66719. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66720. return SceneLoader._getDefaultPlugin();
  66721. };
  66722. SceneLoader._getPluginForDirectLoad = function (data) {
  66723. for (var extension in SceneLoader._registeredPlugins) {
  66724. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66725. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66726. return SceneLoader._registeredPlugins[extension];
  66727. }
  66728. }
  66729. return SceneLoader._getDefaultPlugin();
  66730. };
  66731. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66732. if (sceneFilename.name) {
  66733. sceneFilename = sceneFilename.name;
  66734. }
  66735. var queryStringPosition = sceneFilename.indexOf("?");
  66736. if (queryStringPosition !== -1) {
  66737. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66738. }
  66739. var dotPosition = sceneFilename.lastIndexOf(".");
  66740. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66741. return SceneLoader._getPluginForExtension(extension);
  66742. };
  66743. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66744. SceneLoader._getDirectLoad = function (sceneFilename) {
  66745. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66746. return sceneFilename.substr(5);
  66747. }
  66748. return null;
  66749. };
  66750. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66751. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66752. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66753. var plugin;
  66754. if (registeredPlugin.plugin.createPlugin) {
  66755. plugin = registeredPlugin.plugin.createPlugin();
  66756. }
  66757. else {
  66758. plugin = registeredPlugin.plugin;
  66759. }
  66760. var useArrayBuffer = registeredPlugin.isBinary;
  66761. var database;
  66762. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66763. var dataCallback = function (data, responseURL) {
  66764. if (scene.isDisposed) {
  66765. onError("Scene has been disposed");
  66766. return;
  66767. }
  66768. scene.database = database;
  66769. onSuccess(plugin, data, responseURL);
  66770. };
  66771. var request = null;
  66772. var pluginDisposed = false;
  66773. var onDisposeObservable = plugin.onDisposeObservable;
  66774. if (onDisposeObservable) {
  66775. onDisposeObservable.add(function () {
  66776. pluginDisposed = true;
  66777. if (request) {
  66778. request.abort();
  66779. request = null;
  66780. }
  66781. onDispose();
  66782. });
  66783. }
  66784. var manifestChecked = function () {
  66785. if (pluginDisposed) {
  66786. return;
  66787. }
  66788. var url = rootUrl + sceneFilename;
  66789. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66790. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66791. } : undefined, database, useArrayBuffer, function (request, exception) {
  66792. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66793. });
  66794. };
  66795. if (directLoad) {
  66796. dataCallback(directLoad);
  66797. return plugin;
  66798. }
  66799. if (rootUrl.indexOf("file:") === -1) {
  66800. var engine = scene.getEngine();
  66801. var canUseOfflineSupport = engine.enableOfflineSupport;
  66802. if (canUseOfflineSupport) {
  66803. // Also check for exceptions
  66804. var exceptionFound = false;
  66805. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66806. var regex = _a[_i];
  66807. if (regex.test(rootUrl + sceneFilename)) {
  66808. exceptionFound = true;
  66809. break;
  66810. }
  66811. }
  66812. canUseOfflineSupport = !exceptionFound;
  66813. }
  66814. if (canUseOfflineSupport) {
  66815. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66816. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66817. }
  66818. else {
  66819. manifestChecked();
  66820. }
  66821. }
  66822. // Loading file from disk via input file or drag'n'drop
  66823. else {
  66824. var fileOrString = sceneFilename;
  66825. if (fileOrString.name) { // File
  66826. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66827. }
  66828. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66829. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66830. }
  66831. else {
  66832. onError("Unable to find file named " + sceneFilename);
  66833. }
  66834. }
  66835. return plugin;
  66836. };
  66837. // Public functions
  66838. SceneLoader.GetPluginForExtension = function (extension) {
  66839. return SceneLoader._getPluginForExtension(extension).plugin;
  66840. };
  66841. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66842. return !!SceneLoader._registeredPlugins[extension];
  66843. };
  66844. SceneLoader.RegisterPlugin = function (plugin) {
  66845. if (typeof plugin.extensions === "string") {
  66846. var extension = plugin.extensions;
  66847. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66848. plugin: plugin,
  66849. isBinary: false
  66850. };
  66851. }
  66852. else {
  66853. var extensions = plugin.extensions;
  66854. Object.keys(extensions).forEach(function (extension) {
  66855. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66856. plugin: plugin,
  66857. isBinary: extensions[extension].isBinary
  66858. };
  66859. });
  66860. }
  66861. };
  66862. /**
  66863. * Import meshes into a scene
  66864. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66865. * @param rootUrl a string that defines the root url for scene and resources
  66866. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66867. * @param scene the instance of BABYLON.Scene to append to
  66868. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66869. * @param onProgress a callback with a progress event for each file being loaded
  66870. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66871. * @param pluginExtension the extension used to determine the plugin
  66872. * @returns The loaded plugin
  66873. */
  66874. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66875. if (onSuccess === void 0) { onSuccess = null; }
  66876. if (onProgress === void 0) { onProgress = null; }
  66877. if (onError === void 0) { onError = null; }
  66878. if (pluginExtension === void 0) { pluginExtension = null; }
  66879. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66880. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66881. return null;
  66882. }
  66883. var loadingToken = {};
  66884. scene._addPendingData(loadingToken);
  66885. var disposeHandler = function () {
  66886. scene._removePendingData(loadingToken);
  66887. };
  66888. var errorHandler = function (message, exception) {
  66889. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66890. if (onError) {
  66891. onError(scene, errorMessage, exception);
  66892. }
  66893. else {
  66894. BABYLON.Tools.Error(errorMessage);
  66895. // should the exception be thrown?
  66896. }
  66897. disposeHandler();
  66898. };
  66899. var progressHandler = onProgress ? function (event) {
  66900. try {
  66901. onProgress(event);
  66902. }
  66903. catch (e) {
  66904. errorHandler("Error in onProgress callback", e);
  66905. }
  66906. } : undefined;
  66907. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66908. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66909. if (onSuccess) {
  66910. try {
  66911. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66912. }
  66913. catch (e) {
  66914. errorHandler("Error in onSuccess callback", e);
  66915. }
  66916. }
  66917. scene._removePendingData(loadingToken);
  66918. };
  66919. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66920. if (plugin.rewriteRootURL) {
  66921. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66922. }
  66923. if (sceneFilename === "") {
  66924. if (sceneFilename === "") {
  66925. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66926. }
  66927. }
  66928. if (plugin.importMesh) {
  66929. var syncedPlugin = plugin;
  66930. var meshes = new Array();
  66931. var particleSystems = new Array();
  66932. var skeletons = new Array();
  66933. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66934. return;
  66935. }
  66936. scene.loadingPluginName = plugin.name;
  66937. successHandler(meshes, particleSystems, skeletons, []);
  66938. }
  66939. else {
  66940. var asyncedPlugin = plugin;
  66941. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66942. scene.loadingPluginName = plugin.name;
  66943. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66944. }).catch(function (error) {
  66945. errorHandler(error.message, error);
  66946. });
  66947. }
  66948. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66949. };
  66950. /**
  66951. * Import meshes into a scene
  66952. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66953. * @param rootUrl a string that defines the root url for scene and resources
  66954. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66955. * @param scene the instance of BABYLON.Scene to append to
  66956. * @param onProgress a callback with a progress event for each file being loaded
  66957. * @param pluginExtension the extension used to determine the plugin
  66958. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66959. */
  66960. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66961. if (onProgress === void 0) { onProgress = null; }
  66962. if (pluginExtension === void 0) { pluginExtension = null; }
  66963. return new Promise(function (resolve, reject) {
  66964. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66965. resolve({
  66966. meshes: meshes,
  66967. particleSystems: particleSystems,
  66968. skeletons: skeletons,
  66969. animationGroups: animationGroups
  66970. });
  66971. }, onProgress, function (scene, message, exception) {
  66972. reject(exception || new Error(message));
  66973. }, pluginExtension);
  66974. });
  66975. };
  66976. /**
  66977. * Load a scene
  66978. * @param rootUrl a string that defines the root url for scene and resources
  66979. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66980. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66981. * @param onSuccess a callback with the scene when import succeeds
  66982. * @param onProgress a callback with a progress event for each file being loaded
  66983. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66984. * @param pluginExtension the extension used to determine the plugin
  66985. * @returns The loaded plugin
  66986. */
  66987. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66988. if (onSuccess === void 0) { onSuccess = null; }
  66989. if (onProgress === void 0) { onProgress = null; }
  66990. if (onError === void 0) { onError = null; }
  66991. if (pluginExtension === void 0) { pluginExtension = null; }
  66992. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66993. };
  66994. /**
  66995. * Load a scene
  66996. * @param rootUrl a string that defines the root url for scene and resources
  66997. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66998. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66999. * @param onProgress a callback with a progress event for each file being loaded
  67000. * @param pluginExtension the extension used to determine the plugin
  67001. * @returns The loaded scene
  67002. */
  67003. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67004. if (onProgress === void 0) { onProgress = null; }
  67005. if (pluginExtension === void 0) { pluginExtension = null; }
  67006. return new Promise(function (resolve, reject) {
  67007. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67008. resolve(scene);
  67009. }, onProgress, function (scene, message, exception) {
  67010. reject(exception || new Error(message));
  67011. }, pluginExtension);
  67012. });
  67013. };
  67014. /**
  67015. * Append a scene
  67016. * @param rootUrl a string that defines the root url for scene and resources
  67017. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67018. * @param scene is the instance of BABYLON.Scene to append to
  67019. * @param onSuccess a callback with the scene when import succeeds
  67020. * @param onProgress a callback with a progress event for each file being loaded
  67021. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67022. * @param pluginExtension the extension used to determine the plugin
  67023. * @returns The loaded plugin
  67024. */
  67025. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67026. if (onSuccess === void 0) { onSuccess = null; }
  67027. if (onProgress === void 0) { onProgress = null; }
  67028. if (onError === void 0) { onError = null; }
  67029. if (pluginExtension === void 0) { pluginExtension = null; }
  67030. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67031. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67032. return null;
  67033. }
  67034. if (SceneLoader.ShowLoadingScreen) {
  67035. scene.getEngine().displayLoadingUI();
  67036. }
  67037. var loadingToken = {};
  67038. scene._addPendingData(loadingToken);
  67039. var disposeHandler = function () {
  67040. scene._removePendingData(loadingToken);
  67041. scene.getEngine().hideLoadingUI();
  67042. };
  67043. var errorHandler = function (message, exception) {
  67044. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67045. if (onError) {
  67046. onError(scene, errorMessage, exception);
  67047. }
  67048. else {
  67049. BABYLON.Tools.Error(errorMessage);
  67050. // should the exception be thrown?
  67051. }
  67052. disposeHandler();
  67053. };
  67054. var progressHandler = onProgress ? function (event) {
  67055. try {
  67056. onProgress(event);
  67057. }
  67058. catch (e) {
  67059. errorHandler("Error in onProgress callback", e);
  67060. }
  67061. } : undefined;
  67062. var successHandler = function () {
  67063. if (onSuccess) {
  67064. try {
  67065. onSuccess(scene);
  67066. }
  67067. catch (e) {
  67068. errorHandler("Error in onSuccess callback", e);
  67069. }
  67070. }
  67071. scene._removePendingData(loadingToken);
  67072. };
  67073. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67074. if (sceneFilename === "") {
  67075. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67076. }
  67077. if (plugin.load) {
  67078. var syncedPlugin = plugin;
  67079. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67080. return;
  67081. }
  67082. scene.loadingPluginName = plugin.name;
  67083. successHandler();
  67084. }
  67085. else {
  67086. var asyncedPlugin = plugin;
  67087. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67088. scene.loadingPluginName = plugin.name;
  67089. successHandler();
  67090. }).catch(function (error) {
  67091. errorHandler(error.message, error);
  67092. });
  67093. }
  67094. if (SceneLoader.ShowLoadingScreen) {
  67095. scene.executeWhenReady(function () {
  67096. scene.getEngine().hideLoadingUI();
  67097. });
  67098. }
  67099. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67100. };
  67101. /**
  67102. * Append a scene
  67103. * @param rootUrl a string that defines the root url for scene and resources
  67104. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67105. * @param scene is the instance of BABYLON.Scene to append to
  67106. * @param onProgress a callback with a progress event for each file being loaded
  67107. * @param pluginExtension the extension used to determine the plugin
  67108. * @returns The given scene
  67109. */
  67110. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67111. if (onProgress === void 0) { onProgress = null; }
  67112. if (pluginExtension === void 0) { pluginExtension = null; }
  67113. return new Promise(function (resolve, reject) {
  67114. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67115. resolve(scene);
  67116. }, onProgress, function (scene, message, exception) {
  67117. reject(exception || new Error(message));
  67118. }, pluginExtension);
  67119. });
  67120. };
  67121. /**
  67122. * Load a scene into an asset container
  67123. * @param rootUrl a string that defines the root url for scene and resources
  67124. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67125. * @param scene is the instance of BABYLON.Scene to append to
  67126. * @param onSuccess a callback with the scene when import succeeds
  67127. * @param onProgress a callback with a progress event for each file being loaded
  67128. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67129. * @param pluginExtension the extension used to determine the plugin
  67130. * @returns The loaded plugin
  67131. */
  67132. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67133. if (onSuccess === void 0) { onSuccess = null; }
  67134. if (onProgress === void 0) { onProgress = null; }
  67135. if (onError === void 0) { onError = null; }
  67136. if (pluginExtension === void 0) { pluginExtension = null; }
  67137. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67138. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67139. return null;
  67140. }
  67141. var loadingToken = {};
  67142. scene._addPendingData(loadingToken);
  67143. var disposeHandler = function () {
  67144. scene._removePendingData(loadingToken);
  67145. };
  67146. var errorHandler = function (message, exception) {
  67147. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67148. if (onError) {
  67149. onError(scene, errorMessage, exception);
  67150. }
  67151. else {
  67152. BABYLON.Tools.Error(errorMessage);
  67153. // should the exception be thrown?
  67154. }
  67155. disposeHandler();
  67156. };
  67157. var progressHandler = onProgress ? function (event) {
  67158. try {
  67159. onProgress(event);
  67160. }
  67161. catch (e) {
  67162. errorHandler("Error in onProgress callback", e);
  67163. }
  67164. } : undefined;
  67165. var successHandler = function (assets) {
  67166. if (onSuccess) {
  67167. try {
  67168. onSuccess(assets);
  67169. }
  67170. catch (e) {
  67171. errorHandler("Error in onSuccess callback", e);
  67172. }
  67173. }
  67174. scene._removePendingData(loadingToken);
  67175. };
  67176. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67177. if (plugin.loadAssetContainer) {
  67178. var syncedPlugin = plugin;
  67179. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67180. if (!assetContainer) {
  67181. return;
  67182. }
  67183. scene.loadingPluginName = plugin.name;
  67184. successHandler(assetContainer);
  67185. }
  67186. else if (plugin.loadAssetContainerAsync) {
  67187. var asyncedPlugin = plugin;
  67188. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67189. scene.loadingPluginName = plugin.name;
  67190. successHandler(assetContainer);
  67191. }).catch(function (error) {
  67192. errorHandler(error.message, error);
  67193. });
  67194. }
  67195. else {
  67196. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67197. }
  67198. if (SceneLoader.ShowLoadingScreen) {
  67199. scene.executeWhenReady(function () {
  67200. scene.getEngine().hideLoadingUI();
  67201. });
  67202. }
  67203. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67204. };
  67205. /**
  67206. * Load a scene into an asset container
  67207. * @param rootUrl a string that defines the root url for scene and resources
  67208. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67209. * @param scene is the instance of BABYLON.Scene to append to
  67210. * @param onProgress a callback with a progress event for each file being loaded
  67211. * @param pluginExtension the extension used to determine the plugin
  67212. * @returns The loaded asset container
  67213. */
  67214. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67215. if (onProgress === void 0) { onProgress = null; }
  67216. if (pluginExtension === void 0) { pluginExtension = null; }
  67217. return new Promise(function (resolve, reject) {
  67218. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67219. resolve(assetContainer);
  67220. }, onProgress, function (scene, message, exception) {
  67221. reject(exception || new Error(message));
  67222. }, pluginExtension);
  67223. });
  67224. };
  67225. // Flags
  67226. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67227. SceneLoader._ShowLoadingScreen = true;
  67228. SceneLoader._CleanBoneMatrixWeights = false;
  67229. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67230. // Members
  67231. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67232. SceneLoader._registeredPlugins = {};
  67233. return SceneLoader;
  67234. }());
  67235. BABYLON.SceneLoader = SceneLoader;
  67236. ;
  67237. })(BABYLON || (BABYLON = {}));
  67238. //# sourceMappingURL=babylon.sceneLoader.js.map
  67239. var BABYLON;
  67240. (function (BABYLON) {
  67241. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67242. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67243. var parsedMaterial = parsedData.materials[index];
  67244. if (parsedMaterial.id === id) {
  67245. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67246. }
  67247. }
  67248. return null;
  67249. };
  67250. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67251. for (var i in names) {
  67252. if (mesh.name === names[i]) {
  67253. hierarchyIds.push(mesh.id);
  67254. return true;
  67255. }
  67256. }
  67257. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67258. hierarchyIds.push(mesh.id);
  67259. return true;
  67260. }
  67261. return false;
  67262. };
  67263. var logOperation = function (operation, producer) {
  67264. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67265. };
  67266. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67267. if (addToScene === void 0) { addToScene = false; }
  67268. var container = new BABYLON.AssetContainer(scene);
  67269. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67270. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67271. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67272. // and avoid problems with multiple concurrent .babylon loads.
  67273. var log = "importScene has failed JSON parse";
  67274. try {
  67275. var parsedData = JSON.parse(data);
  67276. log = "";
  67277. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67278. var index;
  67279. var cache;
  67280. // Lights
  67281. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67282. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67283. var parsedLight = parsedData.lights[index];
  67284. var light = BABYLON.Light.Parse(parsedLight, scene);
  67285. if (light) {
  67286. container.lights.push(light);
  67287. log += (index === 0 ? "\n\tLights:" : "");
  67288. log += "\n\t\t" + light.toString(fullDetails);
  67289. }
  67290. }
  67291. }
  67292. // Animations
  67293. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67294. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67295. var parsedAnimation = parsedData.animations[index];
  67296. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67297. scene.animations.push(animation);
  67298. container.animations.push(animation);
  67299. log += (index === 0 ? "\n\tAnimations:" : "");
  67300. log += "\n\t\t" + animation.toString(fullDetails);
  67301. }
  67302. }
  67303. // Materials
  67304. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67305. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67306. var parsedMaterial = parsedData.materials[index];
  67307. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67308. container.materials.push(mat);
  67309. log += (index === 0 ? "\n\tMaterials:" : "");
  67310. log += "\n\t\t" + mat.toString(fullDetails);
  67311. }
  67312. }
  67313. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67314. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67315. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67316. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67317. container.multiMaterials.push(mmat);
  67318. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67319. log += "\n\t\t" + mmat.toString(fullDetails);
  67320. }
  67321. }
  67322. // Morph targets
  67323. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67324. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67325. var managerData = _a[_i];
  67326. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67327. }
  67328. }
  67329. // Skeletons
  67330. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67331. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67332. var parsedSkeleton = parsedData.skeletons[index];
  67333. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67334. container.skeletons.push(skeleton);
  67335. log += (index === 0 ? "\n\tSkeletons:" : "");
  67336. log += "\n\t\t" + skeleton.toString(fullDetails);
  67337. }
  67338. }
  67339. // Geometries
  67340. var geometries = parsedData.geometries;
  67341. if (geometries !== undefined && geometries !== null) {
  67342. var addedGeometry = new Array();
  67343. // Boxes
  67344. var boxes = geometries.boxes;
  67345. if (boxes !== undefined && boxes !== null) {
  67346. for (index = 0, cache = boxes.length; index < cache; index++) {
  67347. var parsedBox = boxes[index];
  67348. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67349. }
  67350. }
  67351. // Spheres
  67352. var spheres = geometries.spheres;
  67353. if (spheres !== undefined && spheres !== null) {
  67354. for (index = 0, cache = spheres.length; index < cache; index++) {
  67355. var parsedSphere = spheres[index];
  67356. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67357. }
  67358. }
  67359. // Cylinders
  67360. var cylinders = geometries.cylinders;
  67361. if (cylinders !== undefined && cylinders !== null) {
  67362. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67363. var parsedCylinder = cylinders[index];
  67364. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67365. }
  67366. }
  67367. // Toruses
  67368. var toruses = geometries.toruses;
  67369. if (toruses !== undefined && toruses !== null) {
  67370. for (index = 0, cache = toruses.length; index < cache; index++) {
  67371. var parsedTorus = toruses[index];
  67372. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67373. }
  67374. }
  67375. // Grounds
  67376. var grounds = geometries.grounds;
  67377. if (grounds !== undefined && grounds !== null) {
  67378. for (index = 0, cache = grounds.length; index < cache; index++) {
  67379. var parsedGround = grounds[index];
  67380. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67381. }
  67382. }
  67383. // Planes
  67384. var planes = geometries.planes;
  67385. if (planes !== undefined && planes !== null) {
  67386. for (index = 0, cache = planes.length; index < cache; index++) {
  67387. var parsedPlane = planes[index];
  67388. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67389. }
  67390. }
  67391. // TorusKnots
  67392. var torusKnots = geometries.torusKnots;
  67393. if (torusKnots !== undefined && torusKnots !== null) {
  67394. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67395. var parsedTorusKnot = torusKnots[index];
  67396. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67397. }
  67398. }
  67399. // VertexData
  67400. var vertexData = geometries.vertexData;
  67401. if (vertexData !== undefined && vertexData !== null) {
  67402. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67403. var parsedVertexData = vertexData[index];
  67404. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67405. }
  67406. }
  67407. addedGeometry.forEach(function (g) {
  67408. if (g) {
  67409. container.geometries.push(g);
  67410. }
  67411. });
  67412. }
  67413. // Transform nodes
  67414. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67415. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67416. var parsedTransformNode = parsedData.transformNodes[index];
  67417. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67418. container.transformNodes.push(node);
  67419. }
  67420. }
  67421. // Meshes
  67422. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67423. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67424. var parsedMesh = parsedData.meshes[index];
  67425. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67426. container.meshes.push(mesh);
  67427. log += (index === 0 ? "\n\tMeshes:" : "");
  67428. log += "\n\t\t" + mesh.toString(fullDetails);
  67429. }
  67430. }
  67431. // Cameras
  67432. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67433. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67434. var parsedCamera = parsedData.cameras[index];
  67435. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67436. container.cameras.push(camera);
  67437. log += (index === 0 ? "\n\tCameras:" : "");
  67438. log += "\n\t\t" + camera.toString(fullDetails);
  67439. }
  67440. }
  67441. // Browsing all the graph to connect the dots
  67442. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67443. var camera = scene.cameras[index];
  67444. if (camera._waitingParentId) {
  67445. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67446. camera._waitingParentId = null;
  67447. }
  67448. }
  67449. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67450. var light_1 = scene.lights[index];
  67451. if (light_1 && light_1._waitingParentId) {
  67452. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67453. light_1._waitingParentId = null;
  67454. }
  67455. }
  67456. // Sounds
  67457. // TODO: add sound
  67458. var loadedSounds = [];
  67459. var loadedSound;
  67460. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67461. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67462. var parsedSound = parsedData.sounds[index];
  67463. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67464. if (!parsedSound.url)
  67465. parsedSound.url = parsedSound.name;
  67466. if (!loadedSounds[parsedSound.url]) {
  67467. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67468. loadedSounds[parsedSound.url] = loadedSound;
  67469. container.sounds.push(loadedSound);
  67470. }
  67471. else {
  67472. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67473. }
  67474. }
  67475. else {
  67476. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67477. }
  67478. }
  67479. }
  67480. loadedSounds = [];
  67481. // Connect parents & children and parse actions
  67482. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67483. var transformNode = scene.transformNodes[index];
  67484. if (transformNode._waitingParentId) {
  67485. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67486. transformNode._waitingParentId = null;
  67487. }
  67488. }
  67489. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67490. var mesh = scene.meshes[index];
  67491. if (mesh._waitingParentId) {
  67492. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67493. mesh._waitingParentId = null;
  67494. }
  67495. if (mesh._waitingActions) {
  67496. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67497. mesh._waitingActions = null;
  67498. }
  67499. }
  67500. // freeze world matrix application
  67501. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67502. var currentMesh = scene.meshes[index];
  67503. if (currentMesh._waitingFreezeWorldMatrix) {
  67504. currentMesh.freezeWorldMatrix();
  67505. currentMesh._waitingFreezeWorldMatrix = null;
  67506. }
  67507. else {
  67508. currentMesh.computeWorldMatrix(true);
  67509. }
  67510. }
  67511. // Particles Systems
  67512. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67513. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67514. var parsedParticleSystem = parsedData.particleSystems[index];
  67515. if (parsedParticleSystem.activeParticleCount) {
  67516. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67517. container.particleSystems.push(ps);
  67518. }
  67519. else {
  67520. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67521. container.particleSystems.push(ps);
  67522. }
  67523. }
  67524. }
  67525. // Lens flares
  67526. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67527. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67528. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67529. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67530. container.lensFlareSystems.push(lf);
  67531. }
  67532. }
  67533. // Shadows
  67534. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67535. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67536. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67537. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67538. container.shadowGenerators.push(sg);
  67539. }
  67540. }
  67541. // Lights exclusions / inclusions
  67542. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67543. var light_2 = scene.lights[index];
  67544. // Excluded check
  67545. if (light_2._excludedMeshesIds.length > 0) {
  67546. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67547. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67548. if (excludedMesh) {
  67549. light_2.excludedMeshes.push(excludedMesh);
  67550. }
  67551. }
  67552. light_2._excludedMeshesIds = [];
  67553. }
  67554. // Included check
  67555. if (light_2._includedOnlyMeshesIds.length > 0) {
  67556. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67557. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67558. if (includedOnlyMesh) {
  67559. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67560. }
  67561. }
  67562. light_2._includedOnlyMeshesIds = [];
  67563. }
  67564. }
  67565. // Effect layers
  67566. if (parsedData.effectLayers) {
  67567. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67568. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67569. container.effectLayers.push(effectLayer);
  67570. }
  67571. }
  67572. // Actions (scene)
  67573. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67574. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67575. }
  67576. if (!addToScene) {
  67577. container.removeAllFromScene();
  67578. }
  67579. }
  67580. catch (err) {
  67581. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67582. if (onError) {
  67583. onError(msg, err);
  67584. }
  67585. else {
  67586. BABYLON.Tools.Log(msg);
  67587. throw err;
  67588. }
  67589. }
  67590. finally {
  67591. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67592. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67593. }
  67594. }
  67595. return container;
  67596. };
  67597. BABYLON.SceneLoader.RegisterPlugin({
  67598. name: "babylon.js",
  67599. extensions: ".babylon",
  67600. canDirectLoad: function (data) {
  67601. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67602. return true;
  67603. }
  67604. return false;
  67605. },
  67606. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67607. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67608. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67609. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67610. // and avoid problems with multiple concurrent .babylon loads.
  67611. var log = "importMesh has failed JSON parse";
  67612. try {
  67613. var parsedData = JSON.parse(data);
  67614. log = "";
  67615. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67616. if (!meshesNames) {
  67617. meshesNames = null;
  67618. }
  67619. else if (!Array.isArray(meshesNames)) {
  67620. meshesNames = [meshesNames];
  67621. }
  67622. var hierarchyIds = new Array();
  67623. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67624. var loadedSkeletonsIds = [];
  67625. var loadedMaterialsIds = [];
  67626. var index;
  67627. var cache;
  67628. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67629. var parsedMesh = parsedData.meshes[index];
  67630. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67631. if (meshesNames !== null) {
  67632. // Remove found mesh name from list.
  67633. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67634. }
  67635. //Geometry?
  67636. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67637. //does the file contain geometries?
  67638. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67639. //find the correct geometry and add it to the scene
  67640. var found = false;
  67641. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67642. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67643. return;
  67644. }
  67645. else {
  67646. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67647. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67648. switch (geometryType) {
  67649. case "boxes":
  67650. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67651. break;
  67652. case "spheres":
  67653. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67654. break;
  67655. case "cylinders":
  67656. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67657. break;
  67658. case "toruses":
  67659. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67660. break;
  67661. case "grounds":
  67662. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67663. break;
  67664. case "planes":
  67665. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67666. break;
  67667. case "torusKnots":
  67668. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67669. break;
  67670. case "vertexData":
  67671. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67672. break;
  67673. }
  67674. found = true;
  67675. }
  67676. });
  67677. }
  67678. });
  67679. if (found === false) {
  67680. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67681. }
  67682. }
  67683. }
  67684. // Material ?
  67685. if (parsedMesh.materialId) {
  67686. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67687. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67688. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67689. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67690. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67691. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67692. var subMatId = parsedMultiMaterial.materials[matIndex];
  67693. loadedMaterialsIds.push(subMatId);
  67694. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67695. if (mat) {
  67696. log += "\n\tMaterial " + mat.toString(fullDetails);
  67697. }
  67698. }
  67699. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67700. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67701. if (mmat) {
  67702. materialFound = true;
  67703. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67704. }
  67705. break;
  67706. }
  67707. }
  67708. }
  67709. if (materialFound === false) {
  67710. loadedMaterialsIds.push(parsedMesh.materialId);
  67711. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67712. if (!mat) {
  67713. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67714. }
  67715. else {
  67716. log += "\n\tMaterial " + mat.toString(fullDetails);
  67717. }
  67718. }
  67719. }
  67720. // Skeleton ?
  67721. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67722. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67723. if (skeletonAlreadyLoaded === false) {
  67724. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67725. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67726. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67727. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67728. skeletons.push(skeleton);
  67729. loadedSkeletonsIds.push(parsedSkeleton.id);
  67730. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67731. }
  67732. }
  67733. }
  67734. }
  67735. // Morph targets ?
  67736. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67737. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67738. var managerData = _a[_i];
  67739. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67740. }
  67741. }
  67742. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67743. meshes.push(mesh);
  67744. log += "\n\tMesh " + mesh.toString(fullDetails);
  67745. }
  67746. }
  67747. // Connecting parents
  67748. var currentMesh;
  67749. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67750. currentMesh = scene.meshes[index];
  67751. if (currentMesh._waitingParentId) {
  67752. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67753. currentMesh._waitingParentId = null;
  67754. }
  67755. }
  67756. // freeze and compute world matrix application
  67757. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67758. currentMesh = scene.meshes[index];
  67759. if (currentMesh._waitingFreezeWorldMatrix) {
  67760. currentMesh.freezeWorldMatrix();
  67761. currentMesh._waitingFreezeWorldMatrix = null;
  67762. }
  67763. else {
  67764. currentMesh.computeWorldMatrix(true);
  67765. }
  67766. }
  67767. }
  67768. // Particles
  67769. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67770. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67771. var parsedParticleSystem = parsedData.particleSystems[index];
  67772. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67773. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67774. }
  67775. }
  67776. }
  67777. return true;
  67778. }
  67779. catch (err) {
  67780. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67781. if (onError) {
  67782. onError(msg, err);
  67783. }
  67784. else {
  67785. BABYLON.Tools.Log(msg);
  67786. throw err;
  67787. }
  67788. }
  67789. finally {
  67790. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67791. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67792. }
  67793. }
  67794. return false;
  67795. },
  67796. load: function (scene, data, rootUrl, onError) {
  67797. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67798. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67799. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67800. // and avoid problems with multiple concurrent .babylon loads.
  67801. var log = "importScene has failed JSON parse";
  67802. try {
  67803. var parsedData = JSON.parse(data);
  67804. log = "";
  67805. // Scene
  67806. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67807. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67808. }
  67809. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67810. scene.autoClear = parsedData.autoClear;
  67811. }
  67812. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67813. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67814. }
  67815. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67816. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67817. }
  67818. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67819. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67820. }
  67821. // Fog
  67822. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67823. scene.fogMode = parsedData.fogMode;
  67824. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67825. scene.fogStart = parsedData.fogStart;
  67826. scene.fogEnd = parsedData.fogEnd;
  67827. scene.fogDensity = parsedData.fogDensity;
  67828. log += "\tFog mode for scene: ";
  67829. switch (scene.fogMode) {
  67830. // getters not compiling, so using hardcoded
  67831. case 1:
  67832. log += "exp\n";
  67833. break;
  67834. case 2:
  67835. log += "exp2\n";
  67836. break;
  67837. case 3:
  67838. log += "linear\n";
  67839. break;
  67840. }
  67841. }
  67842. //Physics
  67843. if (parsedData.physicsEnabled) {
  67844. var physicsPlugin;
  67845. if (parsedData.physicsEngine === "cannon") {
  67846. physicsPlugin = new BABYLON.CannonJSPlugin();
  67847. }
  67848. else if (parsedData.physicsEngine === "oimo") {
  67849. physicsPlugin = new BABYLON.OimoJSPlugin();
  67850. }
  67851. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67852. //else - default engine, which is currently oimo
  67853. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67854. scene.enablePhysics(physicsGravity, physicsPlugin);
  67855. }
  67856. // Metadata
  67857. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67858. scene.metadata = parsedData.metadata;
  67859. }
  67860. //collisions, if defined. otherwise, default is true
  67861. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67862. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67863. }
  67864. scene.workerCollisions = !!parsedData.workerCollisions;
  67865. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67866. if (!container) {
  67867. return false;
  67868. }
  67869. if (parsedData.autoAnimate) {
  67870. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67871. }
  67872. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67873. scene.setActiveCameraByID(parsedData.activeCameraID);
  67874. }
  67875. // Environment texture
  67876. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67877. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  67878. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  67879. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  67880. if (parsedData.environmentTextureRotationY) {
  67881. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  67882. }
  67883. scene.environmentTexture = hdrTexture;
  67884. }
  67885. else {
  67886. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67887. if (parsedData.environmentTextureRotationY) {
  67888. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  67889. }
  67890. scene.environmentTexture = cubeTexture;
  67891. }
  67892. if (parsedData.createDefaultSkybox === true) {
  67893. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67894. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67895. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67896. }
  67897. }
  67898. // Finish
  67899. return true;
  67900. }
  67901. catch (err) {
  67902. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67903. if (onError) {
  67904. onError(msg, err);
  67905. }
  67906. else {
  67907. BABYLON.Tools.Log(msg);
  67908. throw err;
  67909. }
  67910. }
  67911. finally {
  67912. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67913. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67914. }
  67915. }
  67916. return false;
  67917. },
  67918. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67919. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67920. return container;
  67921. }
  67922. });
  67923. })(BABYLON || (BABYLON = {}));
  67924. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67925. var BABYLON;
  67926. (function (BABYLON) {
  67927. var FilesInput = /** @class */ (function () {
  67928. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67929. this.onProcessFileCallback = function () { return true; };
  67930. this._engine = engine;
  67931. this._currentScene = scene;
  67932. this._sceneLoadedCallback = sceneLoadedCallback;
  67933. this._progressCallback = progressCallback;
  67934. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67935. this._textureLoadingCallback = textureLoadingCallback;
  67936. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67937. this._onReloadCallback = onReloadCallback;
  67938. this._errorCallback = errorCallback;
  67939. }
  67940. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67941. var _this = this;
  67942. if (elementToMonitor) {
  67943. this._elementToMonitor = elementToMonitor;
  67944. this._dragEnterHandler = function (e) { _this.drag(e); };
  67945. this._dragOverHandler = function (e) { _this.drag(e); };
  67946. this._dropHandler = function (e) { _this.drop(e); };
  67947. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67948. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67949. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67950. }
  67951. };
  67952. FilesInput.prototype.dispose = function () {
  67953. if (!this._elementToMonitor) {
  67954. return;
  67955. }
  67956. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67957. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67958. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67959. };
  67960. FilesInput.prototype.renderFunction = function () {
  67961. if (this._additionalRenderLoopLogicCallback) {
  67962. this._additionalRenderLoopLogicCallback();
  67963. }
  67964. if (this._currentScene) {
  67965. if (this._textureLoadingCallback) {
  67966. var remaining = this._currentScene.getWaitingItemsCount();
  67967. if (remaining > 0) {
  67968. this._textureLoadingCallback(remaining);
  67969. }
  67970. }
  67971. this._currentScene.render();
  67972. }
  67973. };
  67974. FilesInput.prototype.drag = function (e) {
  67975. e.stopPropagation();
  67976. e.preventDefault();
  67977. };
  67978. FilesInput.prototype.drop = function (eventDrop) {
  67979. eventDrop.stopPropagation();
  67980. eventDrop.preventDefault();
  67981. this.loadFiles(eventDrop);
  67982. };
  67983. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67984. var _this = this;
  67985. var reader = folder.createReader();
  67986. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67987. reader.readEntries(function (entries) {
  67988. remaining.count += entries.length;
  67989. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67990. var entry = entries_1[_i];
  67991. if (entry.isFile) {
  67992. entry.file(function (file) {
  67993. file.correctName = relativePath + file.name;
  67994. files.push(file);
  67995. if (--remaining.count === 0) {
  67996. callback();
  67997. }
  67998. });
  67999. }
  68000. else if (entry.isDirectory) {
  68001. _this._traverseFolder(entry, files, remaining, callback);
  68002. }
  68003. }
  68004. if (--remaining.count) {
  68005. callback();
  68006. }
  68007. });
  68008. };
  68009. FilesInput.prototype._processFiles = function (files) {
  68010. for (var i = 0; i < files.length; i++) {
  68011. var name = files[i].correctName.toLowerCase();
  68012. var extension = name.split('.').pop();
  68013. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68014. continue;
  68015. }
  68016. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68017. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68018. this._sceneFileToLoad = files[i];
  68019. }
  68020. else {
  68021. FilesInput.FilesToLoad[name] = files[i];
  68022. }
  68023. }
  68024. };
  68025. FilesInput.prototype.loadFiles = function (event) {
  68026. var _this = this;
  68027. if (this._startingProcessingFilesCallback)
  68028. this._startingProcessingFilesCallback();
  68029. // Handling data transfer via drag'n'drop
  68030. if (event && event.dataTransfer && event.dataTransfer.files) {
  68031. this._filesToLoad = event.dataTransfer.files;
  68032. }
  68033. // Handling files from input files
  68034. if (event && event.target && event.target.files) {
  68035. this._filesToLoad = event.target.files;
  68036. }
  68037. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68038. var files_1 = new Array();
  68039. var folders = [];
  68040. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68041. for (var i = 0; i < this._filesToLoad.length; i++) {
  68042. var fileToLoad = this._filesToLoad[i];
  68043. var name_1 = fileToLoad.name.toLowerCase();
  68044. var entry = void 0;
  68045. fileToLoad.correctName = name_1;
  68046. if (items) {
  68047. var item = items[i];
  68048. if (item.getAsEntry) {
  68049. entry = item.getAsEntry();
  68050. }
  68051. else if (item.webkitGetAsEntry) {
  68052. entry = item.webkitGetAsEntry();
  68053. }
  68054. }
  68055. if (!entry) {
  68056. files_1.push(fileToLoad);
  68057. }
  68058. else {
  68059. if (entry.isDirectory) {
  68060. folders.push(entry);
  68061. }
  68062. else {
  68063. files_1.push(fileToLoad);
  68064. }
  68065. }
  68066. }
  68067. if (folders.length === 0) {
  68068. this._processFiles(files_1);
  68069. this._processReload();
  68070. }
  68071. else {
  68072. var remaining = { count: folders.length };
  68073. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68074. var folder = folders_1[_i];
  68075. this._traverseFolder(folder, files_1, remaining, function () {
  68076. _this._processFiles(files_1);
  68077. if (remaining.count === 0) {
  68078. _this._processReload();
  68079. }
  68080. });
  68081. }
  68082. }
  68083. }
  68084. };
  68085. FilesInput.prototype._processReload = function () {
  68086. if (this._onReloadCallback) {
  68087. this._onReloadCallback(this._sceneFileToLoad);
  68088. }
  68089. else {
  68090. this.reload();
  68091. }
  68092. };
  68093. FilesInput.prototype.reload = function () {
  68094. var _this = this;
  68095. // If a scene file has been provided
  68096. if (this._sceneFileToLoad) {
  68097. if (this._currentScene) {
  68098. if (BABYLON.Tools.errorsCount > 0) {
  68099. BABYLON.Tools.ClearLogCache();
  68100. }
  68101. this._engine.stopRenderLoop();
  68102. this._currentScene.dispose();
  68103. }
  68104. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68105. if (_this._progressCallback) {
  68106. _this._progressCallback(progress);
  68107. }
  68108. }).then(function (scene) {
  68109. _this._currentScene = scene;
  68110. if (_this._sceneLoadedCallback) {
  68111. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68112. }
  68113. // Wait for textures and shaders to be ready
  68114. _this._currentScene.executeWhenReady(function () {
  68115. _this._engine.runRenderLoop(function () {
  68116. _this.renderFunction();
  68117. });
  68118. });
  68119. }).catch(function (error) {
  68120. if (_this._errorCallback) {
  68121. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68122. }
  68123. });
  68124. }
  68125. else {
  68126. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68127. }
  68128. };
  68129. FilesInput.FilesToLoad = {};
  68130. return FilesInput;
  68131. }());
  68132. BABYLON.FilesInput = FilesInput;
  68133. })(BABYLON || (BABYLON = {}));
  68134. //# sourceMappingURL=babylon.filesInput.js.map
  68135. var BABYLON;
  68136. (function (BABYLON) {
  68137. /**
  68138. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68139. * The underlying implementation relies on an associative array to ensure the best performances.
  68140. * The value can be anything including 'null' but except 'undefined'
  68141. */
  68142. var StringDictionary = /** @class */ (function () {
  68143. function StringDictionary() {
  68144. this._count = 0;
  68145. this._data = {};
  68146. }
  68147. /**
  68148. * This will clear this dictionary and copy the content from the 'source' one.
  68149. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68150. * @param source the dictionary to take the content from and copy to this dictionary
  68151. */
  68152. StringDictionary.prototype.copyFrom = function (source) {
  68153. var _this = this;
  68154. this.clear();
  68155. source.forEach(function (t, v) { return _this.add(t, v); });
  68156. };
  68157. /**
  68158. * Get a value based from its key
  68159. * @param key the given key to get the matching value from
  68160. * @return the value if found, otherwise undefined is returned
  68161. */
  68162. StringDictionary.prototype.get = function (key) {
  68163. var val = this._data[key];
  68164. if (val !== undefined) {
  68165. return val;
  68166. }
  68167. return undefined;
  68168. };
  68169. /**
  68170. * Get a value from its key or add it if it doesn't exist.
  68171. * This method will ensure you that a given key/data will be present in the dictionary.
  68172. * @param key the given key to get the matching value from
  68173. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68174. * The factory will only be invoked if there's no data for the given key.
  68175. * @return the value corresponding to the key.
  68176. */
  68177. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68178. var val = this.get(key);
  68179. if (val !== undefined) {
  68180. return val;
  68181. }
  68182. val = factory(key);
  68183. if (val) {
  68184. this.add(key, val);
  68185. }
  68186. return val;
  68187. };
  68188. /**
  68189. * Get a value from its key if present in the dictionary otherwise add it
  68190. * @param key the key to get the value from
  68191. * @param val if there's no such key/value pair in the dictionary add it with this value
  68192. * @return the value corresponding to the key
  68193. */
  68194. StringDictionary.prototype.getOrAdd = function (key, val) {
  68195. var curVal = this.get(key);
  68196. if (curVal !== undefined) {
  68197. return curVal;
  68198. }
  68199. this.add(key, val);
  68200. return val;
  68201. };
  68202. /**
  68203. * Check if there's a given key in the dictionary
  68204. * @param key the key to check for
  68205. * @return true if the key is present, false otherwise
  68206. */
  68207. StringDictionary.prototype.contains = function (key) {
  68208. return this._data[key] !== undefined;
  68209. };
  68210. /**
  68211. * Add a new key and its corresponding value
  68212. * @param key the key to add
  68213. * @param value the value corresponding to the key
  68214. * @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
  68215. */
  68216. StringDictionary.prototype.add = function (key, value) {
  68217. if (this._data[key] !== undefined) {
  68218. return false;
  68219. }
  68220. this._data[key] = value;
  68221. ++this._count;
  68222. return true;
  68223. };
  68224. StringDictionary.prototype.set = function (key, value) {
  68225. if (this._data[key] === undefined) {
  68226. return false;
  68227. }
  68228. this._data[key] = value;
  68229. return true;
  68230. };
  68231. /**
  68232. * Get the element of the given key and remove it from the dictionary
  68233. * @param key
  68234. */
  68235. StringDictionary.prototype.getAndRemove = function (key) {
  68236. var val = this.get(key);
  68237. if (val !== undefined) {
  68238. delete this._data[key];
  68239. --this._count;
  68240. return val;
  68241. }
  68242. return null;
  68243. };
  68244. /**
  68245. * Remove a key/value from the dictionary.
  68246. * @param key the key to remove
  68247. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68248. */
  68249. StringDictionary.prototype.remove = function (key) {
  68250. if (this.contains(key)) {
  68251. delete this._data[key];
  68252. --this._count;
  68253. return true;
  68254. }
  68255. return false;
  68256. };
  68257. /**
  68258. * Clear the whole content of the dictionary
  68259. */
  68260. StringDictionary.prototype.clear = function () {
  68261. this._data = {};
  68262. this._count = 0;
  68263. };
  68264. Object.defineProperty(StringDictionary.prototype, "count", {
  68265. get: function () {
  68266. return this._count;
  68267. },
  68268. enumerable: true,
  68269. configurable: true
  68270. });
  68271. /**
  68272. * Execute a callback on each key/val of the dictionary.
  68273. * Note that you can remove any element in this dictionary in the callback implementation
  68274. * @param callback the callback to execute on a given key/value pair
  68275. */
  68276. StringDictionary.prototype.forEach = function (callback) {
  68277. for (var cur in this._data) {
  68278. var val = this._data[cur];
  68279. callback(cur, val);
  68280. }
  68281. };
  68282. /**
  68283. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68284. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68285. * Note that you can remove any element in this dictionary in the callback implementation
  68286. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68287. */
  68288. StringDictionary.prototype.first = function (callback) {
  68289. for (var cur in this._data) {
  68290. var val = this._data[cur];
  68291. var res = callback(cur, val);
  68292. if (res) {
  68293. return res;
  68294. }
  68295. }
  68296. return null;
  68297. };
  68298. return StringDictionary;
  68299. }());
  68300. BABYLON.StringDictionary = StringDictionary;
  68301. })(BABYLON || (BABYLON = {}));
  68302. //# sourceMappingURL=babylon.stringDictionary.js.map
  68303. var BABYLON;
  68304. (function (BABYLON) {
  68305. var Tags = /** @class */ (function () {
  68306. function Tags() {
  68307. }
  68308. Tags.EnableFor = function (obj) {
  68309. obj._tags = obj._tags || {};
  68310. obj.hasTags = function () {
  68311. return Tags.HasTags(obj);
  68312. };
  68313. obj.addTags = function (tagsString) {
  68314. return Tags.AddTagsTo(obj, tagsString);
  68315. };
  68316. obj.removeTags = function (tagsString) {
  68317. return Tags.RemoveTagsFrom(obj, tagsString);
  68318. };
  68319. obj.matchesTagsQuery = function (tagsQuery) {
  68320. return Tags.MatchesQuery(obj, tagsQuery);
  68321. };
  68322. };
  68323. Tags.DisableFor = function (obj) {
  68324. delete obj._tags;
  68325. delete obj.hasTags;
  68326. delete obj.addTags;
  68327. delete obj.removeTags;
  68328. delete obj.matchesTagsQuery;
  68329. };
  68330. Tags.HasTags = function (obj) {
  68331. if (!obj._tags) {
  68332. return false;
  68333. }
  68334. return !BABYLON.Tools.IsEmpty(obj._tags);
  68335. };
  68336. Tags.GetTags = function (obj, asString) {
  68337. if (asString === void 0) { asString = true; }
  68338. if (!obj._tags) {
  68339. return null;
  68340. }
  68341. if (asString) {
  68342. var tagsArray = [];
  68343. for (var tag in obj._tags) {
  68344. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68345. tagsArray.push(tag);
  68346. }
  68347. }
  68348. return tagsArray.join(" ");
  68349. }
  68350. else {
  68351. return obj._tags;
  68352. }
  68353. };
  68354. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68355. // a tag cannot start with '||', '&&', and '!'
  68356. // it cannot contain whitespaces
  68357. Tags.AddTagsTo = function (obj, tagsString) {
  68358. if (!tagsString) {
  68359. return;
  68360. }
  68361. if (typeof tagsString !== "string") {
  68362. return;
  68363. }
  68364. var tags = tagsString.split(" ");
  68365. tags.forEach(function (tag, index, array) {
  68366. Tags._AddTagTo(obj, tag);
  68367. });
  68368. };
  68369. Tags._AddTagTo = function (obj, tag) {
  68370. tag = tag.trim();
  68371. if (tag === "" || tag === "true" || tag === "false") {
  68372. return;
  68373. }
  68374. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68375. return;
  68376. }
  68377. Tags.EnableFor(obj);
  68378. obj._tags[tag] = true;
  68379. };
  68380. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68381. if (!Tags.HasTags(obj)) {
  68382. return;
  68383. }
  68384. var tags = tagsString.split(" ");
  68385. for (var t in tags) {
  68386. Tags._RemoveTagFrom(obj, tags[t]);
  68387. }
  68388. };
  68389. Tags._RemoveTagFrom = function (obj, tag) {
  68390. delete obj._tags[tag];
  68391. };
  68392. Tags.MatchesQuery = function (obj, tagsQuery) {
  68393. if (tagsQuery === undefined) {
  68394. return true;
  68395. }
  68396. if (tagsQuery === "") {
  68397. return Tags.HasTags(obj);
  68398. }
  68399. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68400. };
  68401. return Tags;
  68402. }());
  68403. BABYLON.Tags = Tags;
  68404. })(BABYLON || (BABYLON = {}));
  68405. //# sourceMappingURL=babylon.tags.js.map
  68406. var BABYLON;
  68407. (function (BABYLON) {
  68408. /**
  68409. * Class used to evalaute queries containing `and` and `or` operators
  68410. */
  68411. var AndOrNotEvaluator = /** @class */ (function () {
  68412. function AndOrNotEvaluator() {
  68413. }
  68414. /**
  68415. * Evaluate a query
  68416. * @param query defines the query to evaluate
  68417. * @param evaluateCallback defines the callback used to filter result
  68418. * @returns true if the query matches
  68419. */
  68420. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68421. if (!query.match(/\([^\(\)]*\)/g)) {
  68422. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68423. }
  68424. else {
  68425. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68426. // remove parenthesis
  68427. r = r.slice(1, r.length - 1);
  68428. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68429. });
  68430. }
  68431. if (query === "true") {
  68432. return true;
  68433. }
  68434. if (query === "false") {
  68435. return false;
  68436. }
  68437. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68438. };
  68439. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68440. evaluateCallback = evaluateCallback || (function (r) {
  68441. return r === "true" ? true : false;
  68442. });
  68443. var result;
  68444. var or = parenthesisContent.split("||");
  68445. for (var i in or) {
  68446. if (or.hasOwnProperty(i)) {
  68447. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68448. var and = ori.split("&&");
  68449. if (and.length > 1) {
  68450. for (var j = 0; j < and.length; ++j) {
  68451. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68452. if (andj !== "true" && andj !== "false") {
  68453. if (andj[0] === "!") {
  68454. result = !evaluateCallback(andj.substring(1));
  68455. }
  68456. else {
  68457. result = evaluateCallback(andj);
  68458. }
  68459. }
  68460. else {
  68461. result = andj === "true" ? true : false;
  68462. }
  68463. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68464. ori = "false";
  68465. break;
  68466. }
  68467. }
  68468. }
  68469. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68470. result = true;
  68471. break;
  68472. }
  68473. // result equals false (or undefined)
  68474. if (ori !== "true" && ori !== "false") {
  68475. if (ori[0] === "!") {
  68476. result = !evaluateCallback(ori.substring(1));
  68477. }
  68478. else {
  68479. result = evaluateCallback(ori);
  68480. }
  68481. }
  68482. else {
  68483. result = ori === "true" ? true : false;
  68484. }
  68485. }
  68486. }
  68487. // the whole parenthesis scope is replaced by 'true' or 'false'
  68488. return result ? "true" : "false";
  68489. };
  68490. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68491. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68492. // remove whitespaces
  68493. r = r.replace(/[\s]/g, function () { return ""; });
  68494. return r.length % 2 ? "!" : "";
  68495. });
  68496. booleanString = booleanString.trim();
  68497. if (booleanString === "!true") {
  68498. booleanString = "false";
  68499. }
  68500. else if (booleanString === "!false") {
  68501. booleanString = "true";
  68502. }
  68503. return booleanString;
  68504. };
  68505. return AndOrNotEvaluator;
  68506. }());
  68507. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68508. })(BABYLON || (BABYLON = {}));
  68509. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68510. var BABYLON;
  68511. (function (BABYLON) {
  68512. /**
  68513. * Class used to enable access to IndexedDB
  68514. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68515. */
  68516. var Database = /** @class */ (function () {
  68517. /**
  68518. * Creates a new Database
  68519. * @param urlToScene defines the url to load the scene
  68520. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68521. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68522. */
  68523. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68524. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68525. var _this = this;
  68526. // Handling various flavors of prefixed version of IndexedDB
  68527. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68528. this.callbackManifestChecked = callbackManifestChecked;
  68529. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68530. this.db = null;
  68531. this._enableSceneOffline = false;
  68532. this._enableTexturesOffline = false;
  68533. this.manifestVersionFound = 0;
  68534. this.mustUpdateRessources = false;
  68535. this.hasReachedQuota = false;
  68536. if (!Database.IDBStorageEnabled) {
  68537. this.callbackManifestChecked(true);
  68538. }
  68539. else {
  68540. if (disableManifestCheck) {
  68541. this._enableSceneOffline = true;
  68542. this._enableTexturesOffline = true;
  68543. this.manifestVersionFound = 1;
  68544. BABYLON.Tools.SetImmediate(function () {
  68545. _this.callbackManifestChecked(true);
  68546. });
  68547. }
  68548. else {
  68549. this._checkManifestFile();
  68550. }
  68551. }
  68552. }
  68553. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68554. /**
  68555. * Gets a boolean indicating if scene must be saved in the database
  68556. */
  68557. get: function () {
  68558. return this._enableSceneOffline;
  68559. },
  68560. enumerable: true,
  68561. configurable: true
  68562. });
  68563. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68564. /**
  68565. * Gets a boolean indicating if textures must be saved in the database
  68566. */
  68567. get: function () {
  68568. return this._enableTexturesOffline;
  68569. },
  68570. enumerable: true,
  68571. configurable: true
  68572. });
  68573. Database.prototype._checkManifestFile = function () {
  68574. var _this = this;
  68575. var noManifestFile = function () {
  68576. _this._enableSceneOffline = false;
  68577. _this._enableTexturesOffline = false;
  68578. _this.callbackManifestChecked(false);
  68579. };
  68580. var timeStampUsed = false;
  68581. var manifestURL = this.currentSceneUrl + ".manifest";
  68582. var xhr = new XMLHttpRequest();
  68583. if (navigator.onLine) {
  68584. // Adding a timestamp to by-pass browsers' cache
  68585. timeStampUsed = true;
  68586. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68587. }
  68588. xhr.open("GET", manifestURL, true);
  68589. xhr.addEventListener("load", function () {
  68590. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68591. try {
  68592. var manifestFile = JSON.parse(xhr.response);
  68593. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68594. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68595. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68596. _this.manifestVersionFound = manifestFile.version;
  68597. }
  68598. if (_this.callbackManifestChecked) {
  68599. _this.callbackManifestChecked(true);
  68600. }
  68601. }
  68602. catch (ex) {
  68603. noManifestFile();
  68604. }
  68605. }
  68606. else {
  68607. noManifestFile();
  68608. }
  68609. }, false);
  68610. xhr.addEventListener("error", function (event) {
  68611. if (timeStampUsed) {
  68612. timeStampUsed = false;
  68613. // Let's retry without the timeStamp
  68614. // It could fail when coupled with HTML5 Offline API
  68615. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68616. xhr.open("GET", retryManifestURL, true);
  68617. xhr.send();
  68618. }
  68619. else {
  68620. noManifestFile();
  68621. }
  68622. }, false);
  68623. try {
  68624. xhr.send();
  68625. }
  68626. catch (ex) {
  68627. BABYLON.Tools.Error("Error on XHR send request.");
  68628. this.callbackManifestChecked(false);
  68629. }
  68630. };
  68631. /**
  68632. * Open the database and make it available
  68633. * @param successCallback defines the callback to call on success
  68634. * @param errorCallback defines the callback to call on error
  68635. */
  68636. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68637. var _this = this;
  68638. var handleError = function () {
  68639. _this.isSupported = false;
  68640. if (errorCallback)
  68641. errorCallback();
  68642. };
  68643. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68644. // Your browser doesn't support IndexedDB
  68645. this.isSupported = false;
  68646. if (errorCallback)
  68647. errorCallback();
  68648. }
  68649. else {
  68650. // If the DB hasn't been opened or created yet
  68651. if (!this.db) {
  68652. this.hasReachedQuota = false;
  68653. this.isSupported = true;
  68654. var request = this.idbFactory.open("babylonjs", 1);
  68655. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68656. request.onerror = function (event) {
  68657. handleError();
  68658. };
  68659. // executes when a version change transaction cannot complete due to other active transactions
  68660. request.onblocked = function (event) {
  68661. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68662. handleError();
  68663. };
  68664. // DB has been opened successfully
  68665. request.onsuccess = function (event) {
  68666. _this.db = request.result;
  68667. successCallback();
  68668. };
  68669. // Initialization of the DB. Creating Scenes & Textures stores
  68670. request.onupgradeneeded = function (event) {
  68671. _this.db = (event.target).result;
  68672. if (_this.db) {
  68673. try {
  68674. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68675. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68676. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68677. }
  68678. catch (ex) {
  68679. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68680. handleError();
  68681. }
  68682. }
  68683. };
  68684. }
  68685. // DB has already been created and opened
  68686. else {
  68687. if (successCallback)
  68688. successCallback();
  68689. }
  68690. }
  68691. };
  68692. /**
  68693. * Loads an image from the database
  68694. * @param url defines the url to load from
  68695. * @param image defines the target DOM image
  68696. */
  68697. Database.prototype.loadImageFromDB = function (url, image) {
  68698. var _this = this;
  68699. var completeURL = Database._ReturnFullUrlLocation(url);
  68700. var saveAndLoadImage = function () {
  68701. if (!_this.hasReachedQuota && _this.db !== null) {
  68702. // the texture is not yet in the DB, let's try to save it
  68703. _this._saveImageIntoDBAsync(completeURL, image);
  68704. }
  68705. // If the texture is not in the DB and we've reached the DB quota limit
  68706. // let's load it directly from the web
  68707. else {
  68708. image.src = url;
  68709. }
  68710. };
  68711. if (!this.mustUpdateRessources) {
  68712. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68713. }
  68714. // First time we're download the images or update requested in the manifest file by a version change
  68715. else {
  68716. saveAndLoadImage();
  68717. }
  68718. };
  68719. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68720. if (this.isSupported && this.db !== null) {
  68721. var texture;
  68722. var transaction = this.db.transaction(["textures"]);
  68723. transaction.onabort = function (event) {
  68724. image.src = url;
  68725. };
  68726. transaction.oncomplete = function (event) {
  68727. var blobTextureURL;
  68728. if (texture) {
  68729. var URL = window.URL || window.webkitURL;
  68730. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68731. image.onerror = function () {
  68732. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68733. image.src = url;
  68734. };
  68735. image.src = blobTextureURL;
  68736. }
  68737. else {
  68738. notInDBCallback();
  68739. }
  68740. };
  68741. var getRequest = transaction.objectStore("textures").get(url);
  68742. getRequest.onsuccess = function (event) {
  68743. texture = (event.target).result;
  68744. };
  68745. getRequest.onerror = function (event) {
  68746. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68747. image.src = url;
  68748. };
  68749. }
  68750. else {
  68751. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68752. image.src = url;
  68753. }
  68754. };
  68755. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68756. var _this = this;
  68757. if (this.isSupported) {
  68758. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68759. var generateBlobUrl = function () {
  68760. var blobTextureURL;
  68761. if (blob) {
  68762. var URL = window.URL || window.webkitURL;
  68763. try {
  68764. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68765. }
  68766. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68767. catch (ex) {
  68768. blobTextureURL = URL.createObjectURL(blob);
  68769. }
  68770. }
  68771. if (blobTextureURL) {
  68772. image.src = blobTextureURL;
  68773. }
  68774. };
  68775. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68776. var xhr = new XMLHttpRequest(), blob;
  68777. xhr.open("GET", url, true);
  68778. xhr.responseType = "blob";
  68779. xhr.addEventListener("load", function () {
  68780. if (xhr.status === 200 && _this.db) {
  68781. // Blob as response (XHR2)
  68782. blob = xhr.response;
  68783. var transaction = _this.db.transaction(["textures"], "readwrite");
  68784. // the transaction could abort because of a QuotaExceededError error
  68785. transaction.onabort = function (event) {
  68786. try {
  68787. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68788. var srcElement = (event.srcElement || event.target);
  68789. var error = srcElement.error;
  68790. if (error && error.name === "QuotaExceededError") {
  68791. _this.hasReachedQuota = true;
  68792. }
  68793. }
  68794. catch (ex) { }
  68795. generateBlobUrl();
  68796. };
  68797. transaction.oncomplete = function (event) {
  68798. generateBlobUrl();
  68799. };
  68800. var newTexture = { textureUrl: url, data: blob };
  68801. try {
  68802. // Put the blob into the dabase
  68803. var addRequest = transaction.objectStore("textures").put(newTexture);
  68804. addRequest.onsuccess = function (event) {
  68805. };
  68806. addRequest.onerror = function (event) {
  68807. generateBlobUrl();
  68808. };
  68809. }
  68810. catch (ex) {
  68811. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68812. if (ex.code === 25) {
  68813. Database.IsUASupportingBlobStorage = false;
  68814. }
  68815. image.src = url;
  68816. }
  68817. }
  68818. else {
  68819. image.src = url;
  68820. }
  68821. }, false);
  68822. xhr.addEventListener("error", function (event) {
  68823. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68824. image.src = url;
  68825. }, false);
  68826. xhr.send();
  68827. }
  68828. else {
  68829. image.src = url;
  68830. }
  68831. }
  68832. else {
  68833. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68834. image.src = url;
  68835. }
  68836. };
  68837. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68838. var _this = this;
  68839. var updateVersion = function () {
  68840. // the version is not yet in the DB or we need to update it
  68841. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68842. };
  68843. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68844. };
  68845. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68846. var _this = this;
  68847. if (this.isSupported && this.db) {
  68848. var version;
  68849. try {
  68850. var transaction = this.db.transaction(["versions"]);
  68851. transaction.oncomplete = function (event) {
  68852. if (version) {
  68853. // If the version in the JSON file is different from the version in DB
  68854. if (_this.manifestVersionFound !== version.data) {
  68855. _this.mustUpdateRessources = true;
  68856. updateInDBCallback();
  68857. }
  68858. else {
  68859. callback(version.data);
  68860. }
  68861. }
  68862. // version was not found in DB
  68863. else {
  68864. _this.mustUpdateRessources = true;
  68865. updateInDBCallback();
  68866. }
  68867. };
  68868. transaction.onabort = function (event) {
  68869. callback(-1);
  68870. };
  68871. var getRequest = transaction.objectStore("versions").get(url);
  68872. getRequest.onsuccess = function (event) {
  68873. version = (event.target).result;
  68874. };
  68875. getRequest.onerror = function (event) {
  68876. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68877. callback(-1);
  68878. };
  68879. }
  68880. catch (ex) {
  68881. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68882. callback(-1);
  68883. }
  68884. }
  68885. else {
  68886. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68887. callback(-1);
  68888. }
  68889. };
  68890. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68891. var _this = this;
  68892. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68893. try {
  68894. // Open a transaction to the database
  68895. var transaction = this.db.transaction(["versions"], "readwrite");
  68896. // the transaction could abort because of a QuotaExceededError error
  68897. transaction.onabort = function (event) {
  68898. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68899. var error = event.srcElement['error'];
  68900. if (error && error.name === "QuotaExceededError") {
  68901. _this.hasReachedQuota = true;
  68902. }
  68903. }
  68904. catch (ex) { }
  68905. callback(-1);
  68906. };
  68907. transaction.oncomplete = function (event) {
  68908. callback(_this.manifestVersionFound);
  68909. };
  68910. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68911. // Put the scene into the database
  68912. var addRequest = transaction.objectStore("versions").put(newVersion);
  68913. addRequest.onsuccess = function (event) {
  68914. };
  68915. addRequest.onerror = function (event) {
  68916. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68917. };
  68918. }
  68919. catch (ex) {
  68920. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68921. callback(-1);
  68922. }
  68923. }
  68924. else {
  68925. callback(-1);
  68926. }
  68927. };
  68928. /**
  68929. * Loads a file from database
  68930. * @param url defines the URL to load from
  68931. * @param sceneLoaded defines a callback to call on success
  68932. * @param progressCallBack defines a callback to call when progress changed
  68933. * @param errorCallback defines a callback to call on error
  68934. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  68935. */
  68936. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68937. var _this = this;
  68938. var completeUrl = Database._ReturnFullUrlLocation(url);
  68939. var saveAndLoadFile = function () {
  68940. // the scene is not yet in the DB, let's try to save it
  68941. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68942. };
  68943. this._checkVersionFromDB(completeUrl, function (version) {
  68944. if (version !== -1) {
  68945. if (!_this.mustUpdateRessources) {
  68946. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68947. }
  68948. else {
  68949. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68950. }
  68951. }
  68952. else {
  68953. if (errorCallback) {
  68954. errorCallback();
  68955. }
  68956. }
  68957. });
  68958. };
  68959. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68960. if (this.isSupported && this.db) {
  68961. var targetStore;
  68962. if (url.indexOf(".babylon") !== -1) {
  68963. targetStore = "scenes";
  68964. }
  68965. else {
  68966. targetStore = "textures";
  68967. }
  68968. var file;
  68969. var transaction = this.db.transaction([targetStore]);
  68970. transaction.oncomplete = function (event) {
  68971. if (file) {
  68972. callback(file.data);
  68973. }
  68974. // file was not found in DB
  68975. else {
  68976. notInDBCallback();
  68977. }
  68978. };
  68979. transaction.onabort = function (event) {
  68980. notInDBCallback();
  68981. };
  68982. var getRequest = transaction.objectStore(targetStore).get(url);
  68983. getRequest.onsuccess = function (event) {
  68984. file = (event.target).result;
  68985. };
  68986. getRequest.onerror = function (event) {
  68987. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68988. notInDBCallback();
  68989. };
  68990. }
  68991. else {
  68992. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68993. callback();
  68994. }
  68995. };
  68996. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68997. var _this = this;
  68998. if (this.isSupported) {
  68999. var targetStore;
  69000. if (url.indexOf(".babylon") !== -1) {
  69001. targetStore = "scenes";
  69002. }
  69003. else {
  69004. targetStore = "textures";
  69005. }
  69006. // Create XHR
  69007. var xhr = new XMLHttpRequest();
  69008. var fileData;
  69009. xhr.open("GET", url, true);
  69010. if (useArrayBuffer) {
  69011. xhr.responseType = "arraybuffer";
  69012. }
  69013. if (progressCallback) {
  69014. xhr.onprogress = progressCallback;
  69015. }
  69016. xhr.addEventListener("load", function () {
  69017. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69018. // Blob as response (XHR2)
  69019. //fileData = xhr.responseText;
  69020. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69021. if (!_this.hasReachedQuota && _this.db) {
  69022. // Open a transaction to the database
  69023. var transaction = _this.db.transaction([targetStore], "readwrite");
  69024. // the transaction could abort because of a QuotaExceededError error
  69025. transaction.onabort = function (event) {
  69026. try {
  69027. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69028. var error = event.srcElement['error'];
  69029. if (error && error.name === "QuotaExceededError") {
  69030. _this.hasReachedQuota = true;
  69031. }
  69032. }
  69033. catch (ex) { }
  69034. callback(fileData);
  69035. };
  69036. transaction.oncomplete = function (event) {
  69037. callback(fileData);
  69038. };
  69039. var newFile;
  69040. if (targetStore === "scenes") {
  69041. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69042. }
  69043. else {
  69044. newFile = { textureUrl: url, data: fileData };
  69045. }
  69046. try {
  69047. // Put the scene into the database
  69048. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69049. addRequest.onsuccess = function (event) {
  69050. };
  69051. addRequest.onerror = function (event) {
  69052. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69053. };
  69054. }
  69055. catch (ex) {
  69056. callback(fileData);
  69057. }
  69058. }
  69059. else {
  69060. callback(fileData);
  69061. }
  69062. }
  69063. else {
  69064. callback();
  69065. }
  69066. }, false);
  69067. xhr.addEventListener("error", function (event) {
  69068. BABYLON.Tools.Error("error on XHR request.");
  69069. callback();
  69070. }, false);
  69071. xhr.send();
  69072. }
  69073. else {
  69074. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69075. callback();
  69076. }
  69077. };
  69078. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69079. Database.IsUASupportingBlobStorage = true;
  69080. /** Gets a boolean indicating if Database storate is enabled */
  69081. Database.IDBStorageEnabled = true;
  69082. Database._ParseURL = function (url) {
  69083. var a = document.createElement('a');
  69084. a.href = url;
  69085. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69086. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69087. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69088. return absLocation;
  69089. };
  69090. Database._ReturnFullUrlLocation = function (url) {
  69091. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69092. return (Database._ParseURL(window.location.href) + url);
  69093. }
  69094. else {
  69095. return url;
  69096. }
  69097. };
  69098. return Database;
  69099. }());
  69100. BABYLON.Database = Database;
  69101. })(BABYLON || (BABYLON = {}));
  69102. //# sourceMappingURL=babylon.database.js.map
  69103. var BABYLON;
  69104. (function (BABYLON) {
  69105. var FresnelParameters = /** @class */ (function () {
  69106. function FresnelParameters() {
  69107. this._isEnabled = true;
  69108. this.leftColor = BABYLON.Color3.White();
  69109. this.rightColor = BABYLON.Color3.Black();
  69110. this.bias = 0;
  69111. this.power = 1;
  69112. }
  69113. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69114. get: function () {
  69115. return this._isEnabled;
  69116. },
  69117. set: function (value) {
  69118. if (this._isEnabled === value) {
  69119. return;
  69120. }
  69121. this._isEnabled = value;
  69122. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69123. },
  69124. enumerable: true,
  69125. configurable: true
  69126. });
  69127. FresnelParameters.prototype.clone = function () {
  69128. var newFresnelParameters = new FresnelParameters();
  69129. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69130. return newFresnelParameters;
  69131. };
  69132. FresnelParameters.prototype.serialize = function () {
  69133. var serializationObject = {};
  69134. serializationObject.isEnabled = this.isEnabled;
  69135. serializationObject.leftColor = this.leftColor.asArray();
  69136. serializationObject.rightColor = this.rightColor.asArray();
  69137. serializationObject.bias = this.bias;
  69138. serializationObject.power = this.power;
  69139. return serializationObject;
  69140. };
  69141. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69142. var fresnelParameters = new FresnelParameters();
  69143. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69144. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69145. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69146. fresnelParameters.bias = parsedFresnelParameters.bias;
  69147. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69148. return fresnelParameters;
  69149. };
  69150. return FresnelParameters;
  69151. }());
  69152. BABYLON.FresnelParameters = FresnelParameters;
  69153. })(BABYLON || (BABYLON = {}));
  69154. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69155. var BABYLON;
  69156. (function (BABYLON) {
  69157. var MultiMaterial = /** @class */ (function (_super) {
  69158. __extends(MultiMaterial, _super);
  69159. function MultiMaterial(name, scene) {
  69160. var _this = _super.call(this, name, scene, true) || this;
  69161. scene.multiMaterials.push(_this);
  69162. _this.subMaterials = new Array();
  69163. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69164. return _this;
  69165. }
  69166. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69167. get: function () {
  69168. return this._subMaterials;
  69169. },
  69170. set: function (value) {
  69171. this._subMaterials = value;
  69172. this._hookArray(value);
  69173. },
  69174. enumerable: true,
  69175. configurable: true
  69176. });
  69177. MultiMaterial.prototype._hookArray = function (array) {
  69178. var _this = this;
  69179. var oldPush = array.push;
  69180. array.push = function () {
  69181. var items = [];
  69182. for (var _i = 0; _i < arguments.length; _i++) {
  69183. items[_i] = arguments[_i];
  69184. }
  69185. var result = oldPush.apply(array, items);
  69186. _this._markAllSubMeshesAsTexturesDirty();
  69187. return result;
  69188. };
  69189. var oldSplice = array.splice;
  69190. array.splice = function (index, deleteCount) {
  69191. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69192. _this._markAllSubMeshesAsTexturesDirty();
  69193. return deleted;
  69194. };
  69195. };
  69196. // Properties
  69197. MultiMaterial.prototype.getSubMaterial = function (index) {
  69198. if (index < 0 || index >= this.subMaterials.length) {
  69199. return this.getScene().defaultMaterial;
  69200. }
  69201. return this.subMaterials[index];
  69202. };
  69203. MultiMaterial.prototype.getActiveTextures = function () {
  69204. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69205. if (subMaterial) {
  69206. return subMaterial.getActiveTextures();
  69207. }
  69208. else {
  69209. return [];
  69210. }
  69211. }));
  69212. var _a;
  69213. };
  69214. // Methods
  69215. MultiMaterial.prototype.getClassName = function () {
  69216. return "MultiMaterial";
  69217. };
  69218. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69219. for (var index = 0; index < this.subMaterials.length; index++) {
  69220. var subMaterial = this.subMaterials[index];
  69221. if (subMaterial) {
  69222. if (subMaterial.storeEffectOnSubMeshes) {
  69223. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69224. return false;
  69225. }
  69226. continue;
  69227. }
  69228. if (!subMaterial.isReady(mesh)) {
  69229. return false;
  69230. }
  69231. }
  69232. }
  69233. return true;
  69234. };
  69235. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69236. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69237. for (var index = 0; index < this.subMaterials.length; index++) {
  69238. var subMaterial = null;
  69239. var current = this.subMaterials[index];
  69240. if (cloneChildren && current) {
  69241. subMaterial = current.clone(name + "-" + current.name);
  69242. }
  69243. else {
  69244. subMaterial = this.subMaterials[index];
  69245. }
  69246. newMultiMaterial.subMaterials.push(subMaterial);
  69247. }
  69248. return newMultiMaterial;
  69249. };
  69250. MultiMaterial.prototype.serialize = function () {
  69251. var serializationObject = {};
  69252. serializationObject.name = this.name;
  69253. serializationObject.id = this.id;
  69254. if (BABYLON.Tags) {
  69255. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69256. }
  69257. serializationObject.materials = [];
  69258. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69259. var subMat = this.subMaterials[matIndex];
  69260. if (subMat) {
  69261. serializationObject.materials.push(subMat.id);
  69262. }
  69263. else {
  69264. serializationObject.materials.push(null);
  69265. }
  69266. }
  69267. return serializationObject;
  69268. };
  69269. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69270. var scene = this.getScene();
  69271. if (!scene) {
  69272. return;
  69273. }
  69274. var index = scene.multiMaterials.indexOf(this);
  69275. if (index >= 0) {
  69276. scene.multiMaterials.splice(index, 1);
  69277. }
  69278. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69279. };
  69280. return MultiMaterial;
  69281. }(BABYLON.Material));
  69282. BABYLON.MultiMaterial = MultiMaterial;
  69283. })(BABYLON || (BABYLON = {}));
  69284. //# sourceMappingURL=babylon.multiMaterial.js.map
  69285. var BABYLON;
  69286. (function (BABYLON) {
  69287. var FreeCameraTouchInput = /** @class */ (function () {
  69288. function FreeCameraTouchInput() {
  69289. this._offsetX = null;
  69290. this._offsetY = null;
  69291. this._pointerPressed = new Array();
  69292. this.touchAngularSensibility = 200000.0;
  69293. this.touchMoveSensibility = 250.0;
  69294. }
  69295. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69296. var _this = this;
  69297. var previousPosition = null;
  69298. if (this._pointerInput === undefined) {
  69299. this._onLostFocus = function (evt) {
  69300. _this._offsetX = null;
  69301. _this._offsetY = null;
  69302. };
  69303. this._pointerInput = function (p, s) {
  69304. var evt = p.event;
  69305. if (evt.pointerType === "mouse") {
  69306. return;
  69307. }
  69308. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69309. if (!noPreventDefault) {
  69310. evt.preventDefault();
  69311. }
  69312. _this._pointerPressed.push(evt.pointerId);
  69313. if (_this._pointerPressed.length !== 1) {
  69314. return;
  69315. }
  69316. previousPosition = {
  69317. x: evt.clientX,
  69318. y: evt.clientY
  69319. };
  69320. }
  69321. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69322. if (!noPreventDefault) {
  69323. evt.preventDefault();
  69324. }
  69325. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69326. if (index === -1) {
  69327. return;
  69328. }
  69329. _this._pointerPressed.splice(index, 1);
  69330. if (index != 0) {
  69331. return;
  69332. }
  69333. previousPosition = null;
  69334. _this._offsetX = null;
  69335. _this._offsetY = null;
  69336. }
  69337. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69338. if (!noPreventDefault) {
  69339. evt.preventDefault();
  69340. }
  69341. if (!previousPosition) {
  69342. return;
  69343. }
  69344. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69345. if (index != 0) {
  69346. return;
  69347. }
  69348. _this._offsetX = evt.clientX - previousPosition.x;
  69349. _this._offsetY = -(evt.clientY - previousPosition.y);
  69350. }
  69351. };
  69352. }
  69353. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69354. if (this._onLostFocus) {
  69355. element.addEventListener("blur", this._onLostFocus);
  69356. }
  69357. };
  69358. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69359. if (this._pointerInput && element) {
  69360. if (this._observer) {
  69361. this.camera.getScene().onPointerObservable.remove(this._observer);
  69362. this._observer = null;
  69363. }
  69364. if (this._onLostFocus) {
  69365. element.removeEventListener("blur", this._onLostFocus);
  69366. this._onLostFocus = null;
  69367. }
  69368. this._pointerPressed = [];
  69369. this._offsetX = null;
  69370. this._offsetY = null;
  69371. }
  69372. };
  69373. FreeCameraTouchInput.prototype.checkInputs = function () {
  69374. if (this._offsetX && this._offsetY) {
  69375. var camera = this.camera;
  69376. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69377. if (this._pointerPressed.length > 1) {
  69378. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69379. }
  69380. else {
  69381. var speed = camera._computeLocalCameraSpeed();
  69382. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69383. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69384. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69385. }
  69386. }
  69387. };
  69388. FreeCameraTouchInput.prototype.getClassName = function () {
  69389. return "FreeCameraTouchInput";
  69390. };
  69391. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69392. return "touch";
  69393. };
  69394. __decorate([
  69395. BABYLON.serialize()
  69396. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69397. __decorate([
  69398. BABYLON.serialize()
  69399. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69400. return FreeCameraTouchInput;
  69401. }());
  69402. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69403. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69404. })(BABYLON || (BABYLON = {}));
  69405. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69406. var BABYLON;
  69407. (function (BABYLON) {
  69408. // We're mainly based on the logic defined into the FreeCamera code
  69409. var TouchCamera = /** @class */ (function (_super) {
  69410. __extends(TouchCamera, _super);
  69411. //-- end properties for backward compatibility for inputs
  69412. function TouchCamera(name, position, scene) {
  69413. var _this = _super.call(this, name, position, scene) || this;
  69414. _this.inputs.addTouch();
  69415. _this._setupInputs();
  69416. return _this;
  69417. }
  69418. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69419. //-- Begin properties for backward compatibility for inputs
  69420. get: function () {
  69421. var touch = this.inputs.attached["touch"];
  69422. if (touch)
  69423. return touch.touchAngularSensibility;
  69424. return 0;
  69425. },
  69426. set: function (value) {
  69427. var touch = this.inputs.attached["touch"];
  69428. if (touch)
  69429. touch.touchAngularSensibility = value;
  69430. },
  69431. enumerable: true,
  69432. configurable: true
  69433. });
  69434. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69435. get: function () {
  69436. var touch = this.inputs.attached["touch"];
  69437. if (touch)
  69438. return touch.touchMoveSensibility;
  69439. return 0;
  69440. },
  69441. set: function (value) {
  69442. var touch = this.inputs.attached["touch"];
  69443. if (touch)
  69444. touch.touchMoveSensibility = value;
  69445. },
  69446. enumerable: true,
  69447. configurable: true
  69448. });
  69449. TouchCamera.prototype.getClassName = function () {
  69450. return "TouchCamera";
  69451. };
  69452. TouchCamera.prototype._setupInputs = function () {
  69453. var mouse = this.inputs.attached["mouse"];
  69454. if (mouse) {
  69455. mouse.touchEnabled = false;
  69456. }
  69457. };
  69458. return TouchCamera;
  69459. }(BABYLON.FreeCamera));
  69460. BABYLON.TouchCamera = TouchCamera;
  69461. })(BABYLON || (BABYLON = {}));
  69462. //# sourceMappingURL=babylon.touchCamera.js.map
  69463. var BABYLON;
  69464. (function (BABYLON) {
  69465. var ProceduralTexture = /** @class */ (function (_super) {
  69466. __extends(ProceduralTexture, _super);
  69467. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69468. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69469. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69470. if (isCube === void 0) { isCube = false; }
  69471. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69472. _this.isCube = isCube;
  69473. _this.isEnabled = true;
  69474. _this._currentRefreshId = -1;
  69475. _this._refreshRate = 1;
  69476. _this._vertexBuffers = {};
  69477. _this._uniforms = new Array();
  69478. _this._samplers = new Array();
  69479. _this._textures = {};
  69480. _this._floats = {};
  69481. _this._floatsArrays = {};
  69482. _this._colors3 = {};
  69483. _this._colors4 = {};
  69484. _this._vectors2 = {};
  69485. _this._vectors3 = {};
  69486. _this._matrices = {};
  69487. _this._fallbackTextureUsed = false;
  69488. scene.proceduralTextures.push(_this);
  69489. _this._engine = scene.getEngine();
  69490. _this.name = name;
  69491. _this.isRenderTarget = true;
  69492. _this._size = size;
  69493. _this._generateMipMaps = generateMipMaps;
  69494. _this.setFragment(fragment);
  69495. _this._fallbackTexture = fallbackTexture;
  69496. if (isCube) {
  69497. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69498. _this.setFloat("face", 0);
  69499. }
  69500. else {
  69501. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69502. }
  69503. // VBO
  69504. var vertices = [];
  69505. vertices.push(1, 1);
  69506. vertices.push(-1, 1);
  69507. vertices.push(-1, -1);
  69508. vertices.push(1, -1);
  69509. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69510. _this._createIndexBuffer();
  69511. return _this;
  69512. }
  69513. ProceduralTexture.prototype._createIndexBuffer = function () {
  69514. var engine = this._engine;
  69515. // Indices
  69516. var indices = [];
  69517. indices.push(0);
  69518. indices.push(1);
  69519. indices.push(2);
  69520. indices.push(0);
  69521. indices.push(2);
  69522. indices.push(3);
  69523. this._indexBuffer = engine.createIndexBuffer(indices);
  69524. };
  69525. ProceduralTexture.prototype._rebuild = function () {
  69526. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69527. if (vb) {
  69528. vb._rebuild();
  69529. }
  69530. this._createIndexBuffer();
  69531. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69532. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69533. }
  69534. };
  69535. ProceduralTexture.prototype.reset = function () {
  69536. if (this._effect === undefined) {
  69537. return;
  69538. }
  69539. var engine = this._engine;
  69540. engine._releaseEffect(this._effect);
  69541. };
  69542. ProceduralTexture.prototype.isReady = function () {
  69543. var _this = this;
  69544. var engine = this._engine;
  69545. var shaders;
  69546. if (!this._fragment) {
  69547. return false;
  69548. }
  69549. if (this._fallbackTextureUsed) {
  69550. return true;
  69551. }
  69552. if (this._fragment.fragmentElement !== undefined) {
  69553. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69554. }
  69555. else {
  69556. shaders = { vertex: "procedural", fragment: this._fragment };
  69557. }
  69558. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69559. _this.releaseInternalTexture();
  69560. if (_this._fallbackTexture) {
  69561. _this._texture = _this._fallbackTexture._texture;
  69562. if (_this._texture) {
  69563. _this._texture.incrementReferences();
  69564. }
  69565. }
  69566. _this._fallbackTextureUsed = true;
  69567. });
  69568. return this._effect.isReady();
  69569. };
  69570. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69571. this._currentRefreshId = -1;
  69572. };
  69573. ProceduralTexture.prototype.setFragment = function (fragment) {
  69574. this._fragment = fragment;
  69575. };
  69576. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69577. get: function () {
  69578. return this._refreshRate;
  69579. },
  69580. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69581. set: function (value) {
  69582. this._refreshRate = value;
  69583. this.resetRefreshCounter();
  69584. },
  69585. enumerable: true,
  69586. configurable: true
  69587. });
  69588. ProceduralTexture.prototype._shouldRender = function () {
  69589. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69590. return false;
  69591. }
  69592. if (this._fallbackTextureUsed) {
  69593. return false;
  69594. }
  69595. if (this._currentRefreshId === -1) { // At least render once
  69596. this._currentRefreshId = 1;
  69597. return true;
  69598. }
  69599. if (this.refreshRate === this._currentRefreshId) {
  69600. this._currentRefreshId = 1;
  69601. return true;
  69602. }
  69603. this._currentRefreshId++;
  69604. return false;
  69605. };
  69606. ProceduralTexture.prototype.getRenderSize = function () {
  69607. return this._size;
  69608. };
  69609. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69610. if (this._fallbackTextureUsed) {
  69611. return;
  69612. }
  69613. this.releaseInternalTexture();
  69614. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69615. };
  69616. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69617. if (this._uniforms.indexOf(uniformName) === -1) {
  69618. this._uniforms.push(uniformName);
  69619. }
  69620. };
  69621. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69622. if (this._samplers.indexOf(name) === -1) {
  69623. this._samplers.push(name);
  69624. }
  69625. this._textures[name] = texture;
  69626. return this;
  69627. };
  69628. ProceduralTexture.prototype.setFloat = function (name, value) {
  69629. this._checkUniform(name);
  69630. this._floats[name] = value;
  69631. return this;
  69632. };
  69633. ProceduralTexture.prototype.setFloats = function (name, value) {
  69634. this._checkUniform(name);
  69635. this._floatsArrays[name] = value;
  69636. return this;
  69637. };
  69638. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69639. this._checkUniform(name);
  69640. this._colors3[name] = value;
  69641. return this;
  69642. };
  69643. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69644. this._checkUniform(name);
  69645. this._colors4[name] = value;
  69646. return this;
  69647. };
  69648. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69649. this._checkUniform(name);
  69650. this._vectors2[name] = value;
  69651. return this;
  69652. };
  69653. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69654. this._checkUniform(name);
  69655. this._vectors3[name] = value;
  69656. return this;
  69657. };
  69658. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69659. this._checkUniform(name);
  69660. this._matrices[name] = value;
  69661. return this;
  69662. };
  69663. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69664. var scene = this.getScene();
  69665. if (!scene) {
  69666. return;
  69667. }
  69668. var engine = this._engine;
  69669. // Render
  69670. engine.enableEffect(this._effect);
  69671. engine.setState(false);
  69672. // Texture
  69673. for (var name in this._textures) {
  69674. this._effect.setTexture(name, this._textures[name]);
  69675. }
  69676. // Float
  69677. for (name in this._floats) {
  69678. this._effect.setFloat(name, this._floats[name]);
  69679. }
  69680. // Floats
  69681. for (name in this._floatsArrays) {
  69682. this._effect.setArray(name, this._floatsArrays[name]);
  69683. }
  69684. // Color3
  69685. for (name in this._colors3) {
  69686. this._effect.setColor3(name, this._colors3[name]);
  69687. }
  69688. // Color4
  69689. for (name in this._colors4) {
  69690. var color = this._colors4[name];
  69691. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69692. }
  69693. // Vector2
  69694. for (name in this._vectors2) {
  69695. this._effect.setVector2(name, this._vectors2[name]);
  69696. }
  69697. // Vector3
  69698. for (name in this._vectors3) {
  69699. this._effect.setVector3(name, this._vectors3[name]);
  69700. }
  69701. // Matrix
  69702. for (name in this._matrices) {
  69703. this._effect.setMatrix(name, this._matrices[name]);
  69704. }
  69705. if (!this._texture) {
  69706. return;
  69707. }
  69708. if (this.isCube) {
  69709. for (var face = 0; face < 6; face++) {
  69710. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69711. // VBOs
  69712. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69713. this._effect.setFloat("face", face);
  69714. // Clear
  69715. engine.clear(scene.clearColor, true, true, true);
  69716. // Draw order
  69717. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69718. // Mipmaps
  69719. if (face === 5) {
  69720. engine.generateMipMapsForCubemap(this._texture);
  69721. }
  69722. }
  69723. }
  69724. else {
  69725. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69726. // VBOs
  69727. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69728. // Clear
  69729. engine.clear(scene.clearColor, true, true, true);
  69730. // Draw order
  69731. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69732. }
  69733. // Unbind
  69734. engine.unBindFramebuffer(this._texture, this.isCube);
  69735. if (this.onGenerated) {
  69736. this.onGenerated();
  69737. }
  69738. };
  69739. ProceduralTexture.prototype.clone = function () {
  69740. var textureSize = this.getSize();
  69741. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69742. // Base texture
  69743. newTexture.hasAlpha = this.hasAlpha;
  69744. newTexture.level = this.level;
  69745. // RenderTarget Texture
  69746. newTexture.coordinatesMode = this.coordinatesMode;
  69747. return newTexture;
  69748. };
  69749. ProceduralTexture.prototype.dispose = function () {
  69750. var scene = this.getScene();
  69751. if (!scene) {
  69752. return;
  69753. }
  69754. var index = scene.proceduralTextures.indexOf(this);
  69755. if (index >= 0) {
  69756. scene.proceduralTextures.splice(index, 1);
  69757. }
  69758. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69759. if (vertexBuffer) {
  69760. vertexBuffer.dispose();
  69761. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69762. }
  69763. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69764. this._indexBuffer = null;
  69765. }
  69766. _super.prototype.dispose.call(this);
  69767. };
  69768. return ProceduralTexture;
  69769. }(BABYLON.Texture));
  69770. BABYLON.ProceduralTexture = ProceduralTexture;
  69771. })(BABYLON || (BABYLON = {}));
  69772. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69773. var BABYLON;
  69774. (function (BABYLON) {
  69775. var CustomProceduralTexture = /** @class */ (function (_super) {
  69776. __extends(CustomProceduralTexture, _super);
  69777. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69778. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69779. _this._animate = true;
  69780. _this._time = 0;
  69781. _this._texturePath = texturePath;
  69782. //Try to load json
  69783. _this.loadJson(texturePath);
  69784. _this.refreshRate = 1;
  69785. return _this;
  69786. }
  69787. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69788. var _this = this;
  69789. var noConfigFile = function () {
  69790. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69791. try {
  69792. _this.setFragment(_this._texturePath);
  69793. }
  69794. catch (ex) {
  69795. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69796. }
  69797. };
  69798. var configFileUrl = jsonUrl + "/config.json";
  69799. var xhr = new XMLHttpRequest();
  69800. xhr.open("GET", configFileUrl, true);
  69801. xhr.addEventListener("load", function () {
  69802. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69803. try {
  69804. _this._config = JSON.parse(xhr.response);
  69805. _this.updateShaderUniforms();
  69806. _this.updateTextures();
  69807. _this.setFragment(_this._texturePath + "/custom");
  69808. _this._animate = _this._config.animate;
  69809. _this.refreshRate = _this._config.refreshrate;
  69810. }
  69811. catch (ex) {
  69812. noConfigFile();
  69813. }
  69814. }
  69815. else {
  69816. noConfigFile();
  69817. }
  69818. }, false);
  69819. xhr.addEventListener("error", function () {
  69820. noConfigFile();
  69821. }, false);
  69822. try {
  69823. xhr.send();
  69824. }
  69825. catch (ex) {
  69826. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69827. }
  69828. };
  69829. CustomProceduralTexture.prototype.isReady = function () {
  69830. if (!_super.prototype.isReady.call(this)) {
  69831. return false;
  69832. }
  69833. for (var name in this._textures) {
  69834. var texture = this._textures[name];
  69835. if (!texture.isReady()) {
  69836. return false;
  69837. }
  69838. }
  69839. return true;
  69840. };
  69841. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69842. var scene = this.getScene();
  69843. if (this._animate && scene) {
  69844. this._time += scene.getAnimationRatio() * 0.03;
  69845. this.updateShaderUniforms();
  69846. }
  69847. _super.prototype.render.call(this, useCameraPostProcess);
  69848. };
  69849. CustomProceduralTexture.prototype.updateTextures = function () {
  69850. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69851. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69852. }
  69853. };
  69854. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69855. if (this._config) {
  69856. for (var j = 0; j < this._config.uniforms.length; j++) {
  69857. var uniform = this._config.uniforms[j];
  69858. switch (uniform.type) {
  69859. case "float":
  69860. this.setFloat(uniform.name, uniform.value);
  69861. break;
  69862. case "color3":
  69863. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69864. break;
  69865. case "color4":
  69866. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69867. break;
  69868. case "vector2":
  69869. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69870. break;
  69871. case "vector3":
  69872. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69873. break;
  69874. }
  69875. }
  69876. }
  69877. this.setFloat("time", this._time);
  69878. };
  69879. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69880. get: function () {
  69881. return this._animate;
  69882. },
  69883. set: function (value) {
  69884. this._animate = value;
  69885. },
  69886. enumerable: true,
  69887. configurable: true
  69888. });
  69889. return CustomProceduralTexture;
  69890. }(BABYLON.ProceduralTexture));
  69891. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69892. })(BABYLON || (BABYLON = {}));
  69893. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69894. var BABYLON;
  69895. (function (BABYLON) {
  69896. var FreeCameraGamepadInput = /** @class */ (function () {
  69897. function FreeCameraGamepadInput() {
  69898. this.gamepadAngularSensibility = 200;
  69899. this.gamepadMoveSensibility = 40;
  69900. // private members
  69901. this._cameraTransform = BABYLON.Matrix.Identity();
  69902. this._deltaTransform = BABYLON.Vector3.Zero();
  69903. this._vector3 = BABYLON.Vector3.Zero();
  69904. this._vector2 = BABYLON.Vector2.Zero();
  69905. }
  69906. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69907. var _this = this;
  69908. var manager = this.camera.getScene().gamepadManager;
  69909. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69910. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69911. // prioritize XBOX gamepads.
  69912. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69913. _this.gamepad = gamepad;
  69914. }
  69915. }
  69916. });
  69917. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69918. if (_this.gamepad === gamepad) {
  69919. _this.gamepad = null;
  69920. }
  69921. });
  69922. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69923. };
  69924. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69925. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69926. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69927. this.gamepad = null;
  69928. };
  69929. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69930. if (this.gamepad && this.gamepad.leftStick) {
  69931. var camera = this.camera;
  69932. var LSValues = this.gamepad.leftStick;
  69933. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69934. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69935. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69936. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69937. var RSValues = this.gamepad.rightStick;
  69938. if (RSValues) {
  69939. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69940. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69941. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69942. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69943. }
  69944. else {
  69945. RSValues = { x: 0, y: 0 };
  69946. }
  69947. if (!camera.rotationQuaternion) {
  69948. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69949. }
  69950. else {
  69951. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69952. }
  69953. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69954. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69955. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69956. camera.cameraDirection.addInPlace(this._deltaTransform);
  69957. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69958. camera.cameraRotation.addInPlace(this._vector2);
  69959. }
  69960. };
  69961. FreeCameraGamepadInput.prototype.getClassName = function () {
  69962. return "FreeCameraGamepadInput";
  69963. };
  69964. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69965. return "gamepad";
  69966. };
  69967. __decorate([
  69968. BABYLON.serialize()
  69969. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69970. __decorate([
  69971. BABYLON.serialize()
  69972. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69973. return FreeCameraGamepadInput;
  69974. }());
  69975. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69976. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69977. })(BABYLON || (BABYLON = {}));
  69978. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69979. var BABYLON;
  69980. (function (BABYLON) {
  69981. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69982. function ArcRotateCameraGamepadInput() {
  69983. this.gamepadRotationSensibility = 80;
  69984. this.gamepadMoveSensibility = 40;
  69985. }
  69986. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69987. var _this = this;
  69988. var manager = this.camera.getScene().gamepadManager;
  69989. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69990. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69991. // prioritize XBOX gamepads.
  69992. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69993. _this.gamepad = gamepad;
  69994. }
  69995. }
  69996. });
  69997. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69998. if (_this.gamepad === gamepad) {
  69999. _this.gamepad = null;
  70000. }
  70001. });
  70002. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70003. };
  70004. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70005. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70006. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70007. this.gamepad = null;
  70008. };
  70009. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70010. if (this.gamepad) {
  70011. var camera = this.camera;
  70012. var RSValues = this.gamepad.rightStick;
  70013. if (RSValues) {
  70014. if (RSValues.x != 0) {
  70015. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70016. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70017. camera.inertialAlphaOffset += normalizedRX;
  70018. }
  70019. }
  70020. if (RSValues.y != 0) {
  70021. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70022. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70023. camera.inertialBetaOffset += normalizedRY;
  70024. }
  70025. }
  70026. }
  70027. var LSValues = this.gamepad.leftStick;
  70028. if (LSValues && LSValues.y != 0) {
  70029. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70030. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70031. this.camera.inertialRadiusOffset -= normalizedLY;
  70032. }
  70033. }
  70034. }
  70035. };
  70036. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70037. return "ArcRotateCameraGamepadInput";
  70038. };
  70039. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70040. return "gamepad";
  70041. };
  70042. __decorate([
  70043. BABYLON.serialize()
  70044. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70045. __decorate([
  70046. BABYLON.serialize()
  70047. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70048. return ArcRotateCameraGamepadInput;
  70049. }());
  70050. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70051. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70052. })(BABYLON || (BABYLON = {}));
  70053. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70054. var BABYLON;
  70055. (function (BABYLON) {
  70056. var GamepadManager = /** @class */ (function () {
  70057. function GamepadManager(_scene) {
  70058. var _this = this;
  70059. this._scene = _scene;
  70060. this._babylonGamepads = [];
  70061. this._oneGamepadConnected = false;
  70062. this._isMonitoring = false;
  70063. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70064. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70065. this._gamepadEventSupported = false;
  70066. }
  70067. else {
  70068. this._gamepadEventSupported = 'GamepadEvent' in window;
  70069. this._gamepadSupport = (navigator.getGamepads ||
  70070. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70071. }
  70072. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70073. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70074. for (var i in _this._babylonGamepads) {
  70075. var gamepad = _this._babylonGamepads[i];
  70076. if (gamepad && gamepad._isConnected) {
  70077. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70078. }
  70079. }
  70080. });
  70081. this._onGamepadConnectedEvent = function (evt) {
  70082. var gamepad = evt.gamepad;
  70083. if (gamepad.index in _this._babylonGamepads) {
  70084. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70085. return;
  70086. }
  70087. }
  70088. var newGamepad;
  70089. if (_this._babylonGamepads[gamepad.index]) {
  70090. newGamepad = _this._babylonGamepads[gamepad.index];
  70091. newGamepad.browserGamepad = gamepad;
  70092. newGamepad._isConnected = true;
  70093. }
  70094. else {
  70095. newGamepad = _this._addNewGamepad(gamepad);
  70096. }
  70097. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70098. _this._startMonitoringGamepads();
  70099. };
  70100. this._onGamepadDisconnectedEvent = function (evt) {
  70101. var gamepad = evt.gamepad;
  70102. // Remove the gamepad from the list of gamepads to monitor.
  70103. for (var i in _this._babylonGamepads) {
  70104. if (_this._babylonGamepads[i].index === gamepad.index) {
  70105. var disconnectedGamepad = _this._babylonGamepads[i];
  70106. disconnectedGamepad._isConnected = false;
  70107. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70108. break;
  70109. }
  70110. }
  70111. };
  70112. if (this._gamepadSupport) {
  70113. //first add already-connected gamepads
  70114. this._updateGamepadObjects();
  70115. if (this._babylonGamepads.length) {
  70116. this._startMonitoringGamepads();
  70117. }
  70118. // Checking if the gamepad connected event is supported (like in Firefox)
  70119. if (this._gamepadEventSupported) {
  70120. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70121. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70122. }
  70123. else {
  70124. this._startMonitoringGamepads();
  70125. }
  70126. }
  70127. }
  70128. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70129. get: function () {
  70130. return this._babylonGamepads;
  70131. },
  70132. enumerable: true,
  70133. configurable: true
  70134. });
  70135. GamepadManager.prototype.getGamepadByType = function (type) {
  70136. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70137. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70138. var gamepad = _a[_i];
  70139. if (gamepad && gamepad.type === type) {
  70140. return gamepad;
  70141. }
  70142. }
  70143. return null;
  70144. };
  70145. GamepadManager.prototype.dispose = function () {
  70146. if (this._gamepadEventSupported) {
  70147. if (this._onGamepadConnectedEvent) {
  70148. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70149. }
  70150. if (this._onGamepadDisconnectedEvent) {
  70151. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70152. }
  70153. this._onGamepadConnectedEvent = null;
  70154. this._onGamepadDisconnectedEvent = null;
  70155. }
  70156. this._babylonGamepads.forEach(function (gamepad) {
  70157. gamepad.dispose();
  70158. });
  70159. this.onGamepadConnectedObservable.clear();
  70160. this.onGamepadDisconnectedObservable.clear();
  70161. this._oneGamepadConnected = false;
  70162. this._stopMonitoringGamepads();
  70163. this._babylonGamepads = [];
  70164. };
  70165. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70166. if (!this._oneGamepadConnected) {
  70167. this._oneGamepadConnected = true;
  70168. }
  70169. var newGamepad;
  70170. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70171. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70172. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70173. }
  70174. // if pose is supported, use the (WebVR) pose enabled controller
  70175. else if (gamepad.pose) {
  70176. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70177. }
  70178. else {
  70179. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70180. }
  70181. this._babylonGamepads[newGamepad.index] = newGamepad;
  70182. return newGamepad;
  70183. };
  70184. GamepadManager.prototype._startMonitoringGamepads = function () {
  70185. if (!this._isMonitoring) {
  70186. this._isMonitoring = true;
  70187. //back-comp
  70188. if (!this._scene) {
  70189. this._checkGamepadsStatus();
  70190. }
  70191. }
  70192. };
  70193. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70194. this._isMonitoring = false;
  70195. };
  70196. GamepadManager.prototype._checkGamepadsStatus = function () {
  70197. var _this = this;
  70198. // Hack to be compatible Chrome
  70199. this._updateGamepadObjects();
  70200. for (var i in this._babylonGamepads) {
  70201. var gamepad = this._babylonGamepads[i];
  70202. if (!gamepad || !gamepad.isConnected) {
  70203. continue;
  70204. }
  70205. gamepad.update();
  70206. }
  70207. if (this._isMonitoring && !this._scene) {
  70208. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70209. }
  70210. };
  70211. // This function is called only on Chrome, which does not properly support
  70212. // connection/disconnection events and forces you to recopy again the gamepad object
  70213. GamepadManager.prototype._updateGamepadObjects = function () {
  70214. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70215. for (var i = 0; i < gamepads.length; i++) {
  70216. var gamepad = gamepads[i];
  70217. if (gamepad) {
  70218. if (!this._babylonGamepads[gamepad.index]) {
  70219. var newGamepad = this._addNewGamepad(gamepad);
  70220. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70221. }
  70222. else {
  70223. // Forced to copy again this object for Chrome for unknown reason
  70224. this._babylonGamepads[i].browserGamepad = gamepad;
  70225. if (!this._babylonGamepads[i].isConnected) {
  70226. this._babylonGamepads[i]._isConnected = true;
  70227. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70228. }
  70229. }
  70230. }
  70231. }
  70232. };
  70233. return GamepadManager;
  70234. }());
  70235. BABYLON.GamepadManager = GamepadManager;
  70236. })(BABYLON || (BABYLON = {}));
  70237. //# sourceMappingURL=babylon.gamepadManager.js.map
  70238. var BABYLON;
  70239. (function (BABYLON) {
  70240. var StickValues = /** @class */ (function () {
  70241. function StickValues(x, y) {
  70242. this.x = x;
  70243. this.y = y;
  70244. }
  70245. return StickValues;
  70246. }());
  70247. BABYLON.StickValues = StickValues;
  70248. var Gamepad = /** @class */ (function () {
  70249. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70250. if (leftStickX === void 0) { leftStickX = 0; }
  70251. if (leftStickY === void 0) { leftStickY = 1; }
  70252. if (rightStickX === void 0) { rightStickX = 2; }
  70253. if (rightStickY === void 0) { rightStickY = 3; }
  70254. this.id = id;
  70255. this.index = index;
  70256. this.browserGamepad = browserGamepad;
  70257. this._isConnected = true;
  70258. this._invertLeftStickY = false;
  70259. this.type = Gamepad.GAMEPAD;
  70260. this._leftStickAxisX = leftStickX;
  70261. this._leftStickAxisY = leftStickY;
  70262. this._rightStickAxisX = rightStickX;
  70263. this._rightStickAxisY = rightStickY;
  70264. if (this.browserGamepad.axes.length >= 2) {
  70265. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70266. }
  70267. if (this.browserGamepad.axes.length >= 4) {
  70268. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70269. }
  70270. }
  70271. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70272. get: function () {
  70273. return this._isConnected;
  70274. },
  70275. enumerable: true,
  70276. configurable: true
  70277. });
  70278. Gamepad.prototype.onleftstickchanged = function (callback) {
  70279. this._onleftstickchanged = callback;
  70280. };
  70281. Gamepad.prototype.onrightstickchanged = function (callback) {
  70282. this._onrightstickchanged = callback;
  70283. };
  70284. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70285. get: function () {
  70286. return this._leftStick;
  70287. },
  70288. set: function (newValues) {
  70289. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70290. this._onleftstickchanged(newValues);
  70291. }
  70292. this._leftStick = newValues;
  70293. },
  70294. enumerable: true,
  70295. configurable: true
  70296. });
  70297. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70298. get: function () {
  70299. return this._rightStick;
  70300. },
  70301. set: function (newValues) {
  70302. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70303. this._onrightstickchanged(newValues);
  70304. }
  70305. this._rightStick = newValues;
  70306. },
  70307. enumerable: true,
  70308. configurable: true
  70309. });
  70310. Gamepad.prototype.update = function () {
  70311. if (this._leftStick) {
  70312. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70313. if (this._invertLeftStickY) {
  70314. this.leftStick.y *= -1;
  70315. }
  70316. }
  70317. if (this._rightStick) {
  70318. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70319. }
  70320. };
  70321. Gamepad.prototype.dispose = function () {
  70322. };
  70323. Gamepad.GAMEPAD = 0;
  70324. Gamepad.GENERIC = 1;
  70325. Gamepad.XBOX = 2;
  70326. Gamepad.POSE_ENABLED = 3;
  70327. return Gamepad;
  70328. }());
  70329. BABYLON.Gamepad = Gamepad;
  70330. var GenericPad = /** @class */ (function (_super) {
  70331. __extends(GenericPad, _super);
  70332. function GenericPad(id, index, browserGamepad) {
  70333. var _this = _super.call(this, id, index, browserGamepad) || this;
  70334. _this.onButtonDownObservable = new BABYLON.Observable();
  70335. _this.onButtonUpObservable = new BABYLON.Observable();
  70336. _this.type = Gamepad.GENERIC;
  70337. _this._buttons = new Array(browserGamepad.buttons.length);
  70338. return _this;
  70339. }
  70340. GenericPad.prototype.onbuttondown = function (callback) {
  70341. this._onbuttondown = callback;
  70342. };
  70343. GenericPad.prototype.onbuttonup = function (callback) {
  70344. this._onbuttonup = callback;
  70345. };
  70346. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70347. if (newValue !== currentValue) {
  70348. if (newValue === 1) {
  70349. if (this._onbuttondown) {
  70350. this._onbuttondown(buttonIndex);
  70351. }
  70352. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70353. }
  70354. if (newValue === 0) {
  70355. if (this._onbuttonup) {
  70356. this._onbuttonup(buttonIndex);
  70357. }
  70358. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70359. }
  70360. }
  70361. return newValue;
  70362. };
  70363. GenericPad.prototype.update = function () {
  70364. _super.prototype.update.call(this);
  70365. for (var index = 0; index < this._buttons.length; index++) {
  70366. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70367. }
  70368. };
  70369. GenericPad.prototype.dispose = function () {
  70370. _super.prototype.dispose.call(this);
  70371. this.onButtonDownObservable.clear();
  70372. this.onButtonUpObservable.clear();
  70373. };
  70374. return GenericPad;
  70375. }(Gamepad));
  70376. BABYLON.GenericPad = GenericPad;
  70377. })(BABYLON || (BABYLON = {}));
  70378. //# sourceMappingURL=babylon.gamepad.js.map
  70379. var BABYLON;
  70380. (function (BABYLON) {
  70381. /**
  70382. * Defines supported buttons for XBox360 compatible gamepads
  70383. */
  70384. var Xbox360Button;
  70385. (function (Xbox360Button) {
  70386. /** A */
  70387. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70388. /** B */
  70389. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70390. /** X */
  70391. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70392. /** Y */
  70393. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70394. /** Start */
  70395. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70396. /** Back */
  70397. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70398. /** Left button */
  70399. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70400. /** Right button */
  70401. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70402. /** Left stick */
  70403. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70404. /** Right stick */
  70405. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70406. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70407. /** Defines values for XBox360 DPad */
  70408. var Xbox360Dpad;
  70409. (function (Xbox360Dpad) {
  70410. /** Up */
  70411. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70412. /** Down */
  70413. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70414. /** Left */
  70415. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70416. /** Right */
  70417. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70418. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70419. /**
  70420. * Defines a XBox360 gamepad
  70421. */
  70422. var Xbox360Pad = /** @class */ (function (_super) {
  70423. __extends(Xbox360Pad, _super);
  70424. /**
  70425. * Creates a new XBox360 gamepad object
  70426. * @param id defines the id of this gamepad
  70427. * @param index defines its index
  70428. * @param gamepad defines the internal HTML gamepad object
  70429. * @param xboxOne defines if it is a XBox One gamepad
  70430. */
  70431. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70432. if (xboxOne === void 0) { xboxOne = false; }
  70433. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70434. _this._leftTrigger = 0;
  70435. _this._rightTrigger = 0;
  70436. /** Observable raised when a button is pressed */
  70437. _this.onButtonDownObservable = new BABYLON.Observable();
  70438. /** Observable raised when a button is released */
  70439. _this.onButtonUpObservable = new BABYLON.Observable();
  70440. /** Observable raised when a pad is pressed */
  70441. _this.onPadDownObservable = new BABYLON.Observable();
  70442. /** Observable raised when a pad is released */
  70443. _this.onPadUpObservable = new BABYLON.Observable();
  70444. _this._buttonA = 0;
  70445. _this._buttonB = 0;
  70446. _this._buttonX = 0;
  70447. _this._buttonY = 0;
  70448. _this._buttonBack = 0;
  70449. _this._buttonStart = 0;
  70450. _this._buttonLB = 0;
  70451. _this._buttonRB = 0;
  70452. _this._buttonLeftStick = 0;
  70453. _this._buttonRightStick = 0;
  70454. _this._dPadUp = 0;
  70455. _this._dPadDown = 0;
  70456. _this._dPadLeft = 0;
  70457. _this._dPadRight = 0;
  70458. _this._isXboxOnePad = false;
  70459. _this.type = BABYLON.Gamepad.XBOX;
  70460. _this._isXboxOnePad = xboxOne;
  70461. return _this;
  70462. }
  70463. /**
  70464. * Defines the callback to call when left trigger is pressed
  70465. * @param callback defines the callback to use
  70466. */
  70467. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70468. this._onlefttriggerchanged = callback;
  70469. };
  70470. /**
  70471. * Defines the callback to call when right trigger is pressed
  70472. * @param callback defines the callback to use
  70473. */
  70474. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70475. this._onrighttriggerchanged = callback;
  70476. };
  70477. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70478. /**
  70479. * Gets or sets left trigger value
  70480. */
  70481. get: function () {
  70482. return this._leftTrigger;
  70483. },
  70484. set: function (newValue) {
  70485. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70486. this._onlefttriggerchanged(newValue);
  70487. }
  70488. this._leftTrigger = newValue;
  70489. },
  70490. enumerable: true,
  70491. configurable: true
  70492. });
  70493. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70494. /**
  70495. * Gets or sets right trigger value
  70496. */
  70497. get: function () {
  70498. return this._rightTrigger;
  70499. },
  70500. set: function (newValue) {
  70501. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70502. this._onrighttriggerchanged(newValue);
  70503. }
  70504. this._rightTrigger = newValue;
  70505. },
  70506. enumerable: true,
  70507. configurable: true
  70508. });
  70509. /**
  70510. * Defines the callback to call when a button is pressed
  70511. * @param callback defines the callback to use
  70512. */
  70513. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70514. this._onbuttondown = callback;
  70515. };
  70516. /**
  70517. * Defines the callback to call when a button is released
  70518. * @param callback defines the callback to use
  70519. */
  70520. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70521. this._onbuttonup = callback;
  70522. };
  70523. /**
  70524. * Defines the callback to call when a pad is pressed
  70525. * @param callback defines the callback to use
  70526. */
  70527. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70528. this._ondpaddown = callback;
  70529. };
  70530. /**
  70531. * Defines the callback to call when a pad is released
  70532. * @param callback defines the callback to use
  70533. */
  70534. Xbox360Pad.prototype.ondpadup = function (callback) {
  70535. this._ondpadup = callback;
  70536. };
  70537. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70538. if (newValue !== currentValue) {
  70539. if (newValue === 1) {
  70540. if (this._onbuttondown) {
  70541. this._onbuttondown(buttonType);
  70542. }
  70543. this.onButtonDownObservable.notifyObservers(buttonType);
  70544. }
  70545. if (newValue === 0) {
  70546. if (this._onbuttonup) {
  70547. this._onbuttonup(buttonType);
  70548. }
  70549. this.onButtonUpObservable.notifyObservers(buttonType);
  70550. }
  70551. }
  70552. return newValue;
  70553. };
  70554. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70555. if (newValue !== currentValue) {
  70556. if (newValue === 1) {
  70557. if (this._ondpaddown) {
  70558. this._ondpaddown(buttonType);
  70559. }
  70560. this.onPadDownObservable.notifyObservers(buttonType);
  70561. }
  70562. if (newValue === 0) {
  70563. if (this._ondpadup) {
  70564. this._ondpadup(buttonType);
  70565. }
  70566. this.onPadUpObservable.notifyObservers(buttonType);
  70567. }
  70568. }
  70569. return newValue;
  70570. };
  70571. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70572. /** Gets or sets value of A button */
  70573. get: function () {
  70574. return this._buttonA;
  70575. },
  70576. set: function (value) {
  70577. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70578. },
  70579. enumerable: true,
  70580. configurable: true
  70581. });
  70582. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70583. /** Gets or sets value of B button */
  70584. get: function () {
  70585. return this._buttonB;
  70586. },
  70587. set: function (value) {
  70588. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70589. },
  70590. enumerable: true,
  70591. configurable: true
  70592. });
  70593. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70594. /** Gets or sets value of X button */
  70595. get: function () {
  70596. return this._buttonX;
  70597. },
  70598. set: function (value) {
  70599. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70600. },
  70601. enumerable: true,
  70602. configurable: true
  70603. });
  70604. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70605. /** Gets or sets value of Y button */
  70606. get: function () {
  70607. return this._buttonY;
  70608. },
  70609. set: function (value) {
  70610. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70611. },
  70612. enumerable: true,
  70613. configurable: true
  70614. });
  70615. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70616. /** Gets or sets value of Start button */
  70617. get: function () {
  70618. return this._buttonStart;
  70619. },
  70620. set: function (value) {
  70621. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70622. },
  70623. enumerable: true,
  70624. configurable: true
  70625. });
  70626. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70627. /** Gets or sets value of Back button */
  70628. get: function () {
  70629. return this._buttonBack;
  70630. },
  70631. set: function (value) {
  70632. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70633. },
  70634. enumerable: true,
  70635. configurable: true
  70636. });
  70637. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70638. /** Gets or sets value of Left button */
  70639. get: function () {
  70640. return this._buttonLB;
  70641. },
  70642. set: function (value) {
  70643. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70644. },
  70645. enumerable: true,
  70646. configurable: true
  70647. });
  70648. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70649. /** Gets or sets value of Right button */
  70650. get: function () {
  70651. return this._buttonRB;
  70652. },
  70653. set: function (value) {
  70654. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70655. },
  70656. enumerable: true,
  70657. configurable: true
  70658. });
  70659. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70660. /** Gets or sets value of left stick */
  70661. get: function () {
  70662. return this._buttonLeftStick;
  70663. },
  70664. set: function (value) {
  70665. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70666. },
  70667. enumerable: true,
  70668. configurable: true
  70669. });
  70670. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70671. /** Gets or sets value of right stick */
  70672. get: function () {
  70673. return this._buttonRightStick;
  70674. },
  70675. set: function (value) {
  70676. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70677. },
  70678. enumerable: true,
  70679. configurable: true
  70680. });
  70681. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70682. /** Gets or sets value of DPad up */
  70683. get: function () {
  70684. return this._dPadUp;
  70685. },
  70686. set: function (value) {
  70687. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70688. },
  70689. enumerable: true,
  70690. configurable: true
  70691. });
  70692. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70693. /** Gets or sets value of DPad down */
  70694. get: function () {
  70695. return this._dPadDown;
  70696. },
  70697. set: function (value) {
  70698. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70699. },
  70700. enumerable: true,
  70701. configurable: true
  70702. });
  70703. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70704. /** Gets or sets value of DPad left */
  70705. get: function () {
  70706. return this._dPadLeft;
  70707. },
  70708. set: function (value) {
  70709. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70710. },
  70711. enumerable: true,
  70712. configurable: true
  70713. });
  70714. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70715. /** Gets or sets value of DPad right */
  70716. get: function () {
  70717. return this._dPadRight;
  70718. },
  70719. set: function (value) {
  70720. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70721. },
  70722. enumerable: true,
  70723. configurable: true
  70724. });
  70725. /**
  70726. * Force the gamepad to synchronize with device values
  70727. */
  70728. Xbox360Pad.prototype.update = function () {
  70729. _super.prototype.update.call(this);
  70730. if (this._isXboxOnePad) {
  70731. this.buttonA = this.browserGamepad.buttons[0].value;
  70732. this.buttonB = this.browserGamepad.buttons[1].value;
  70733. this.buttonX = this.browserGamepad.buttons[2].value;
  70734. this.buttonY = this.browserGamepad.buttons[3].value;
  70735. this.buttonLB = this.browserGamepad.buttons[4].value;
  70736. this.buttonRB = this.browserGamepad.buttons[5].value;
  70737. this.leftTrigger = this.browserGamepad.axes[2];
  70738. this.rightTrigger = this.browserGamepad.axes[5];
  70739. this.buttonBack = this.browserGamepad.buttons[9].value;
  70740. this.buttonStart = this.browserGamepad.buttons[8].value;
  70741. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70742. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70743. this.dPadUp = this.browserGamepad.buttons[11].value;
  70744. this.dPadDown = this.browserGamepad.buttons[12].value;
  70745. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70746. this.dPadRight = this.browserGamepad.buttons[14].value;
  70747. }
  70748. else {
  70749. this.buttonA = this.browserGamepad.buttons[0].value;
  70750. this.buttonB = this.browserGamepad.buttons[1].value;
  70751. this.buttonX = this.browserGamepad.buttons[2].value;
  70752. this.buttonY = this.browserGamepad.buttons[3].value;
  70753. this.buttonLB = this.browserGamepad.buttons[4].value;
  70754. this.buttonRB = this.browserGamepad.buttons[5].value;
  70755. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70756. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70757. this.buttonBack = this.browserGamepad.buttons[8].value;
  70758. this.buttonStart = this.browserGamepad.buttons[9].value;
  70759. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70760. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70761. this.dPadUp = this.browserGamepad.buttons[12].value;
  70762. this.dPadDown = this.browserGamepad.buttons[13].value;
  70763. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70764. this.dPadRight = this.browserGamepad.buttons[15].value;
  70765. }
  70766. };
  70767. Xbox360Pad.prototype.dispose = function () {
  70768. _super.prototype.dispose.call(this);
  70769. this.onButtonDownObservable.clear();
  70770. this.onButtonUpObservable.clear();
  70771. this.onPadDownObservable.clear();
  70772. this.onPadUpObservable.clear();
  70773. };
  70774. return Xbox360Pad;
  70775. }(BABYLON.Gamepad));
  70776. BABYLON.Xbox360Pad = Xbox360Pad;
  70777. })(BABYLON || (BABYLON = {}));
  70778. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70779. var BABYLON;
  70780. (function (BABYLON) {
  70781. /**
  70782. * Defines the types of pose enabled controllers that are supported
  70783. */
  70784. var PoseEnabledControllerType;
  70785. (function (PoseEnabledControllerType) {
  70786. /**
  70787. * HTC Vive
  70788. */
  70789. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70790. /**
  70791. * Oculus Rift
  70792. */
  70793. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70794. /**
  70795. * Windows mixed reality
  70796. */
  70797. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70798. /**
  70799. * Samsung gear VR
  70800. */
  70801. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70802. /**
  70803. * Google Daydream
  70804. */
  70805. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70806. /**
  70807. * Generic
  70808. */
  70809. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70810. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70811. /**
  70812. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70813. */
  70814. var PoseEnabledControllerHelper = /** @class */ (function () {
  70815. function PoseEnabledControllerHelper() {
  70816. }
  70817. /**
  70818. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70819. * @param vrGamepad the gamepad to initialized
  70820. * @returns a vr controller of the type the gamepad identified as
  70821. */
  70822. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70823. // Oculus Touch
  70824. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70825. return new BABYLON.OculusTouchController(vrGamepad);
  70826. }
  70827. // Windows Mixed Reality controllers
  70828. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70829. return new BABYLON.WindowsMotionController(vrGamepad);
  70830. }
  70831. // HTC Vive
  70832. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70833. return new BABYLON.ViveController(vrGamepad);
  70834. }
  70835. // Samsung/Oculus Gear VR
  70836. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70837. return new BABYLON.GearVRController(vrGamepad);
  70838. }
  70839. // Google Daydream
  70840. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70841. return new BABYLON.DaydreamController(vrGamepad);
  70842. }
  70843. // Generic
  70844. else {
  70845. return new BABYLON.GenericController(vrGamepad);
  70846. }
  70847. };
  70848. return PoseEnabledControllerHelper;
  70849. }());
  70850. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70851. /**
  70852. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70853. */
  70854. var PoseEnabledController = /** @class */ (function (_super) {
  70855. __extends(PoseEnabledController, _super);
  70856. /**
  70857. * Creates a new PoseEnabledController from a gamepad
  70858. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70859. */
  70860. function PoseEnabledController(browserGamepad) {
  70861. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70862. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70863. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70864. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70865. /**
  70866. * The device position in babylon space
  70867. */
  70868. _this.devicePosition = BABYLON.Vector3.Zero();
  70869. /**
  70870. * The device rotation in babylon space
  70871. */
  70872. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70873. /**
  70874. * The scale factor of the device in babylon space
  70875. */
  70876. _this.deviceScaleFactor = 1;
  70877. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70878. /**
  70879. * Internal, matrix used to convert room space to babylon space
  70880. */
  70881. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70882. /**
  70883. * Node to be used when casting a ray from the controller
  70884. */
  70885. _this._pointingPoseNode = null;
  70886. _this._workingMatrix = BABYLON.Matrix.Identity();
  70887. /**
  70888. * @hidden
  70889. */
  70890. _this._meshAttachedObservable = new BABYLON.Observable();
  70891. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70892. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70893. _this.position = BABYLON.Vector3.Zero();
  70894. _this.rotationQuaternion = new BABYLON.Quaternion();
  70895. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70896. _this._calculatedRotation = new BABYLON.Quaternion();
  70897. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70898. return _this;
  70899. }
  70900. /**
  70901. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70902. */
  70903. PoseEnabledController.prototype.update = function () {
  70904. _super.prototype.update.call(this);
  70905. var pose = this.browserGamepad.pose;
  70906. this.updateFromDevice(pose);
  70907. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70908. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70909. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70910. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70911. if (this._mesh) {
  70912. this._mesh.position.copyFrom(this.devicePosition);
  70913. if (this._mesh.rotationQuaternion) {
  70914. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70915. }
  70916. }
  70917. };
  70918. /**
  70919. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70920. * @param poseData raw pose fromthe device
  70921. */
  70922. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70923. if (poseData) {
  70924. this.rawPose = poseData;
  70925. if (poseData.position) {
  70926. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70927. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70928. this._deviceRoomPosition.z *= -1;
  70929. }
  70930. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70931. this._calculatedPosition.addInPlace(this.position);
  70932. }
  70933. var pose = this.rawPose;
  70934. if (poseData.orientation && pose.orientation) {
  70935. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70936. if (this._mesh) {
  70937. if (this._mesh.getScene().useRightHandedSystem) {
  70938. this._deviceRoomRotationQuaternion.z *= -1;
  70939. this._deviceRoomRotationQuaternion.w *= -1;
  70940. }
  70941. else {
  70942. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70943. }
  70944. }
  70945. // if the camera is set, rotate to the camera's rotation
  70946. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70947. }
  70948. }
  70949. };
  70950. /**
  70951. * Attaches a mesh to the controller
  70952. * @param mesh the mesh to be attached
  70953. */
  70954. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70955. if (this._mesh) {
  70956. this._mesh.parent = null;
  70957. }
  70958. this._mesh = mesh;
  70959. if (this._poseControlledCamera) {
  70960. this._mesh.parent = this._poseControlledCamera;
  70961. }
  70962. if (!this._mesh.rotationQuaternion) {
  70963. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70964. }
  70965. this._meshAttachedObservable.notifyObservers(mesh);
  70966. };
  70967. /**
  70968. * Attaches the controllers mesh to a camera
  70969. * @param camera the camera the mesh should be attached to
  70970. */
  70971. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70972. this._poseControlledCamera = camera;
  70973. if (this._mesh) {
  70974. this._mesh.parent = this._poseControlledCamera;
  70975. }
  70976. };
  70977. /**
  70978. * Disposes of the controller
  70979. */
  70980. PoseEnabledController.prototype.dispose = function () {
  70981. if (this._mesh) {
  70982. this._mesh.dispose();
  70983. }
  70984. this._mesh = null;
  70985. _super.prototype.dispose.call(this);
  70986. };
  70987. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70988. /**
  70989. * The mesh that is attached to the controller
  70990. */
  70991. get: function () {
  70992. return this._mesh;
  70993. },
  70994. enumerable: true,
  70995. configurable: true
  70996. });
  70997. /**
  70998. * Gets the ray of the controller in the direction the controller is pointing
  70999. * @param length the length the resulting ray should be
  71000. * @returns a ray in the direction the controller is pointing
  71001. */
  71002. PoseEnabledController.prototype.getForwardRay = function (length) {
  71003. if (length === void 0) { length = 100; }
  71004. if (!this.mesh) {
  71005. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71006. }
  71007. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71008. var origin = m.getTranslation();
  71009. var forward = new BABYLON.Vector3(0, 0, -1);
  71010. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71011. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71012. return new BABYLON.Ray(origin, direction, length);
  71013. };
  71014. /**
  71015. * Name of the child mesh that can be used to cast a ray from the controller
  71016. */
  71017. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71018. return PoseEnabledController;
  71019. }(BABYLON.Gamepad));
  71020. BABYLON.PoseEnabledController = PoseEnabledController;
  71021. })(BABYLON || (BABYLON = {}));
  71022. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71023. var BABYLON;
  71024. (function (BABYLON) {
  71025. /**
  71026. * Defines the WebVRController object that represents controllers tracked in 3D space
  71027. */
  71028. var WebVRController = /** @class */ (function (_super) {
  71029. __extends(WebVRController, _super);
  71030. /**
  71031. * Creates a new WebVRController from a gamepad
  71032. * @param vrGamepad the gamepad that the WebVRController should be created from
  71033. */
  71034. function WebVRController(vrGamepad) {
  71035. var _this = _super.call(this, vrGamepad) || this;
  71036. // Observables
  71037. /**
  71038. * Fired when the trigger state has changed
  71039. */
  71040. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71041. /**
  71042. * Fired when the main button state has changed
  71043. */
  71044. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71045. /**
  71046. * Fired when the secondary button state has changed
  71047. */
  71048. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71049. /**
  71050. * Fired when the pad state has changed
  71051. */
  71052. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71053. /**
  71054. * Fired when controllers stick values have changed
  71055. */
  71056. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71057. /**
  71058. * X and Y axis corrisponding to the controllers joystick
  71059. */
  71060. _this.pad = { x: 0, y: 0 };
  71061. // avoid GC, store state in a tmp object
  71062. _this._changes = {
  71063. pressChanged: false,
  71064. touchChanged: false,
  71065. valueChanged: false,
  71066. changed: false
  71067. };
  71068. _this._buttons = new Array(vrGamepad.buttons.length);
  71069. _this.hand = vrGamepad.hand;
  71070. return _this;
  71071. }
  71072. /**
  71073. * Fired when a controller button's state has changed
  71074. * @param callback the callback containing the button that was modified
  71075. */
  71076. WebVRController.prototype.onButtonStateChange = function (callback) {
  71077. this._onButtonStateChange = callback;
  71078. };
  71079. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71080. /**
  71081. * The default controller model for the controller
  71082. */
  71083. get: function () {
  71084. return this._defaultModel;
  71085. },
  71086. enumerable: true,
  71087. configurable: true
  71088. });
  71089. /**
  71090. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71091. */
  71092. WebVRController.prototype.update = function () {
  71093. _super.prototype.update.call(this);
  71094. for (var index = 0; index < this._buttons.length; index++) {
  71095. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71096. }
  71097. ;
  71098. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71099. this.pad.x = this.leftStick.x;
  71100. this.pad.y = this.leftStick.y;
  71101. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71102. }
  71103. };
  71104. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71105. if (!newState) {
  71106. newState = {
  71107. pressed: false,
  71108. touched: false,
  71109. value: 0
  71110. };
  71111. }
  71112. if (!currentState) {
  71113. this._buttons[buttonIndex] = {
  71114. pressed: newState.pressed,
  71115. touched: newState.touched,
  71116. value: newState.value
  71117. };
  71118. return;
  71119. }
  71120. this._checkChanges(newState, currentState);
  71121. if (this._changes.changed) {
  71122. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71123. this._handleButtonChange(buttonIndex, newState, this._changes);
  71124. }
  71125. this._buttons[buttonIndex].pressed = newState.pressed;
  71126. this._buttons[buttonIndex].touched = newState.touched;
  71127. // oculus triggers are never 0, thou not touched.
  71128. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71129. };
  71130. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71131. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71132. this._changes.touchChanged = newState.touched !== currentState.touched;
  71133. this._changes.valueChanged = newState.value !== currentState.value;
  71134. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71135. return this._changes;
  71136. };
  71137. /**
  71138. * Disposes of th webVRCOntroller
  71139. */
  71140. WebVRController.prototype.dispose = function () {
  71141. _super.prototype.dispose.call(this);
  71142. this.onTriggerStateChangedObservable.clear();
  71143. this.onMainButtonStateChangedObservable.clear();
  71144. this.onSecondaryButtonStateChangedObservable.clear();
  71145. this.onPadStateChangedObservable.clear();
  71146. this.onPadValuesChangedObservable.clear();
  71147. };
  71148. return WebVRController;
  71149. }(BABYLON.PoseEnabledController));
  71150. BABYLON.WebVRController = WebVRController;
  71151. })(BABYLON || (BABYLON = {}));
  71152. //# sourceMappingURL=babylon.webVRController.js.map
  71153. var BABYLON;
  71154. (function (BABYLON) {
  71155. /**
  71156. * Oculus Touch Controller
  71157. */
  71158. var OculusTouchController = /** @class */ (function (_super) {
  71159. __extends(OculusTouchController, _super);
  71160. /**
  71161. * Creates a new OculusTouchController from a gamepad
  71162. * @param vrGamepad the gamepad that the controller should be created from
  71163. */
  71164. function OculusTouchController(vrGamepad) {
  71165. var _this = _super.call(this, vrGamepad) || this;
  71166. /**
  71167. * Fired when the secondary trigger on this controller is modified
  71168. */
  71169. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71170. /**
  71171. * Fired when the thumb rest on this controller is modified
  71172. */
  71173. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71174. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71175. return _this;
  71176. }
  71177. /**
  71178. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71179. * @param scene scene in which to add meshes
  71180. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71181. */
  71182. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71183. var _this = this;
  71184. var meshName;
  71185. // Hand
  71186. if (this.hand === 'left') {
  71187. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71188. }
  71189. else { // Right is the default if no hand is specified
  71190. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71191. }
  71192. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71193. /*
  71194. Parent Mesh name: oculus_touch_left
  71195. - body
  71196. - trigger
  71197. - thumbstick
  71198. - grip
  71199. - button_y
  71200. - button_x
  71201. - button_enter
  71202. */
  71203. _this._defaultModel = newMeshes[1];
  71204. _this.attachToMesh(_this._defaultModel);
  71205. if (meshLoaded) {
  71206. meshLoaded(_this._defaultModel);
  71207. }
  71208. });
  71209. };
  71210. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71211. /**
  71212. * Fired when the A button on this controller is modified
  71213. */
  71214. get: function () {
  71215. if (this.hand === 'right') {
  71216. return this.onMainButtonStateChangedObservable;
  71217. }
  71218. else {
  71219. throw new Error('No A button on left hand');
  71220. }
  71221. },
  71222. enumerable: true,
  71223. configurable: true
  71224. });
  71225. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71226. /**
  71227. * Fired when the B button on this controller is modified
  71228. */
  71229. get: function () {
  71230. if (this.hand === 'right') {
  71231. return this.onSecondaryButtonStateChangedObservable;
  71232. }
  71233. else {
  71234. throw new Error('No B button on left hand');
  71235. }
  71236. },
  71237. enumerable: true,
  71238. configurable: true
  71239. });
  71240. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71241. /**
  71242. * Fired when the X button on this controller is modified
  71243. */
  71244. get: function () {
  71245. if (this.hand === 'left') {
  71246. return this.onMainButtonStateChangedObservable;
  71247. }
  71248. else {
  71249. throw new Error('No X button on right hand');
  71250. }
  71251. },
  71252. enumerable: true,
  71253. configurable: true
  71254. });
  71255. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71256. /**
  71257. * Fired when the Y button on this controller is modified
  71258. */
  71259. get: function () {
  71260. if (this.hand === 'left') {
  71261. return this.onSecondaryButtonStateChangedObservable;
  71262. }
  71263. else {
  71264. throw new Error('No Y button on right hand');
  71265. }
  71266. },
  71267. enumerable: true,
  71268. configurable: true
  71269. });
  71270. /**
  71271. * Called once for each button that changed state since the last frame
  71272. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71273. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71274. * 2) secondary trigger (same)
  71275. * 3) A (right) X (left), touch, pressed = value
  71276. * 4) B / Y
  71277. * 5) thumb rest
  71278. * @param buttonIdx Which button index changed
  71279. * @param state New state of the button
  71280. * @param changes Which properties on the state changed since last frame
  71281. */
  71282. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71283. var notifyObject = state; //{ state: state, changes: changes };
  71284. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71285. switch (buttonIdx) {
  71286. case 0:
  71287. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71288. return;
  71289. case 1: // index trigger
  71290. if (this._defaultModel) {
  71291. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71292. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71293. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71294. }
  71295. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71296. return;
  71297. case 2: // secondary trigger
  71298. if (this._defaultModel) {
  71299. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71300. }
  71301. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71302. return;
  71303. case 3:
  71304. if (this._defaultModel) {
  71305. if (notifyObject.pressed) {
  71306. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71307. }
  71308. else {
  71309. (this._defaultModel.getChildren()[1]).position.y = 0;
  71310. }
  71311. }
  71312. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71313. return;
  71314. case 4:
  71315. if (this._defaultModel) {
  71316. if (notifyObject.pressed) {
  71317. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71318. }
  71319. else {
  71320. (this._defaultModel.getChildren()[2]).position.y = 0;
  71321. }
  71322. }
  71323. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71324. return;
  71325. case 5:
  71326. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71327. return;
  71328. }
  71329. };
  71330. /**
  71331. * Base Url for the controller model.
  71332. */
  71333. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71334. /**
  71335. * File name for the left controller model.
  71336. */
  71337. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71338. /**
  71339. * File name for the right controller model.
  71340. */
  71341. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71342. return OculusTouchController;
  71343. }(BABYLON.WebVRController));
  71344. BABYLON.OculusTouchController = OculusTouchController;
  71345. })(BABYLON || (BABYLON = {}));
  71346. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71347. var BABYLON;
  71348. (function (BABYLON) {
  71349. /**
  71350. * Vive Controller
  71351. */
  71352. var ViveController = /** @class */ (function (_super) {
  71353. __extends(ViveController, _super);
  71354. /**
  71355. * Creates a new ViveController from a gamepad
  71356. * @param vrGamepad the gamepad that the controller should be created from
  71357. */
  71358. function ViveController(vrGamepad) {
  71359. var _this = _super.call(this, vrGamepad) || this;
  71360. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71361. _this._invertLeftStickY = true;
  71362. return _this;
  71363. }
  71364. /**
  71365. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71366. * @param scene scene in which to add meshes
  71367. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71368. */
  71369. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71370. var _this = this;
  71371. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71372. /*
  71373. Parent Mesh name: ViveWand
  71374. - body
  71375. - r_gripper
  71376. - l_gripper
  71377. - menu_button
  71378. - system_button
  71379. - trackpad
  71380. - trigger
  71381. - LED
  71382. */
  71383. _this._defaultModel = newMeshes[1];
  71384. _this.attachToMesh(_this._defaultModel);
  71385. if (meshLoaded) {
  71386. meshLoaded(_this._defaultModel);
  71387. }
  71388. });
  71389. };
  71390. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71391. /**
  71392. * Fired when the left button on this controller is modified
  71393. */
  71394. get: function () {
  71395. return this.onMainButtonStateChangedObservable;
  71396. },
  71397. enumerable: true,
  71398. configurable: true
  71399. });
  71400. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71401. /**
  71402. * Fired when the right button on this controller is modified
  71403. */
  71404. get: function () {
  71405. return this.onMainButtonStateChangedObservable;
  71406. },
  71407. enumerable: true,
  71408. configurable: true
  71409. });
  71410. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71411. /**
  71412. * Fired when the menu button on this controller is modified
  71413. */
  71414. get: function () {
  71415. return this.onSecondaryButtonStateChangedObservable;
  71416. },
  71417. enumerable: true,
  71418. configurable: true
  71419. });
  71420. /**
  71421. * Called once for each button that changed state since the last frame
  71422. * Vive mapping:
  71423. * 0: touchpad
  71424. * 1: trigger
  71425. * 2: left AND right buttons
  71426. * 3: menu button
  71427. * @param buttonIdx Which button index changed
  71428. * @param state New state of the button
  71429. * @param changes Which properties on the state changed since last frame
  71430. */
  71431. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71432. var notifyObject = state; //{ state: state, changes: changes };
  71433. switch (buttonIdx) {
  71434. case 0:
  71435. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71436. return;
  71437. case 1: // index trigger
  71438. if (this._defaultModel) {
  71439. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71440. }
  71441. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71442. return;
  71443. case 2: // left AND right button
  71444. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71445. return;
  71446. case 3:
  71447. if (this._defaultModel) {
  71448. if (notifyObject.pressed) {
  71449. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71450. }
  71451. else {
  71452. (this._defaultModel.getChildren()[2]).position.y = 0;
  71453. }
  71454. }
  71455. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71456. return;
  71457. }
  71458. };
  71459. /**
  71460. * Base Url for the controller model.
  71461. */
  71462. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71463. /**
  71464. * File name for the controller model.
  71465. */
  71466. ViveController.MODEL_FILENAME = 'wand.babylon';
  71467. return ViveController;
  71468. }(BABYLON.WebVRController));
  71469. BABYLON.ViveController = ViveController;
  71470. })(BABYLON || (BABYLON = {}));
  71471. //# sourceMappingURL=babylon.viveController.js.map
  71472. var BABYLON;
  71473. (function (BABYLON) {
  71474. /**
  71475. * Generic Controller
  71476. */
  71477. var GenericController = /** @class */ (function (_super) {
  71478. __extends(GenericController, _super);
  71479. /**
  71480. * Creates a new GenericController from a gamepad
  71481. * @param vrGamepad the gamepad that the controller should be created from
  71482. */
  71483. function GenericController(vrGamepad) {
  71484. return _super.call(this, vrGamepad) || this;
  71485. }
  71486. /**
  71487. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71488. * @param scene scene in which to add meshes
  71489. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71490. */
  71491. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71492. var _this = this;
  71493. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71494. _this._defaultModel = newMeshes[1];
  71495. _this.attachToMesh(_this._defaultModel);
  71496. if (meshLoaded) {
  71497. meshLoaded(_this._defaultModel);
  71498. }
  71499. });
  71500. };
  71501. /**
  71502. * Called once for each button that changed state since the last frame
  71503. * @param buttonIdx Which button index changed
  71504. * @param state New state of the button
  71505. * @param changes Which properties on the state changed since last frame
  71506. */
  71507. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71508. console.log("Button id: " + buttonIdx + "state: ");
  71509. console.dir(state);
  71510. };
  71511. /**
  71512. * Base Url for the controller model.
  71513. */
  71514. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71515. /**
  71516. * File name for the controller model.
  71517. */
  71518. GenericController.MODEL_FILENAME = 'generic.babylon';
  71519. return GenericController;
  71520. }(BABYLON.WebVRController));
  71521. BABYLON.GenericController = GenericController;
  71522. })(BABYLON || (BABYLON = {}));
  71523. //# sourceMappingURL=babylon.genericController.js.map
  71524. var BABYLON;
  71525. (function (BABYLON) {
  71526. /**
  71527. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71528. */
  71529. var LoadedMeshInfo = /** @class */ (function () {
  71530. function LoadedMeshInfo() {
  71531. /**
  71532. * Map of the button meshes contained in the controller
  71533. */
  71534. this.buttonMeshes = {};
  71535. /**
  71536. * Map of the axis meshes contained in the controller
  71537. */
  71538. this.axisMeshes = {};
  71539. }
  71540. return LoadedMeshInfo;
  71541. }());
  71542. /**
  71543. * Defines the WindowsMotionController object that the state of the windows motion controller
  71544. */
  71545. var WindowsMotionController = /** @class */ (function (_super) {
  71546. __extends(WindowsMotionController, _super);
  71547. /**
  71548. * Creates a new WindowsMotionController from a gamepad
  71549. * @param vrGamepad the gamepad that the controller should be created from
  71550. */
  71551. function WindowsMotionController(vrGamepad) {
  71552. var _this = _super.call(this, vrGamepad) || this;
  71553. _this._mapping = {
  71554. // Semantic button names
  71555. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71556. // A mapping of the button name to glTF model node name
  71557. // that should be transformed by button value.
  71558. buttonMeshNames: {
  71559. 'trigger': 'SELECT',
  71560. 'menu': 'MENU',
  71561. 'grip': 'GRASP',
  71562. 'thumbstick': 'THUMBSTICK_PRESS',
  71563. 'trackpad': 'TOUCHPAD_PRESS'
  71564. },
  71565. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71566. buttonObservableNames: {
  71567. 'trigger': 'onTriggerStateChangedObservable',
  71568. 'menu': 'onSecondaryButtonStateChangedObservable',
  71569. 'grip': 'onMainButtonStateChangedObservable',
  71570. 'thumbstick': 'onPadStateChangedObservable',
  71571. 'trackpad': 'onTrackpadChangedObservable'
  71572. },
  71573. // A mapping of the axis name to glTF model node name
  71574. // that should be transformed by axis value.
  71575. // This array mirrors the browserGamepad.axes array, such that
  71576. // the mesh corresponding to axis 0 is in this array index 0.
  71577. axisMeshNames: [
  71578. 'THUMBSTICK_X',
  71579. 'THUMBSTICK_Y',
  71580. 'TOUCHPAD_TOUCH_X',
  71581. 'TOUCHPAD_TOUCH_Y'
  71582. ],
  71583. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71584. };
  71585. /**
  71586. * Fired when the trackpad on this controller is clicked
  71587. */
  71588. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71589. /**
  71590. * Fired when the trackpad on this controller is modified
  71591. */
  71592. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71593. /**
  71594. * The current x and y values of this controller's trackpad
  71595. */
  71596. _this.trackpad = { x: 0, y: 0 };
  71597. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71598. _this._loadedMeshInfo = null;
  71599. return _this;
  71600. }
  71601. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71602. /**
  71603. * Fired when the trigger on this controller is modified
  71604. */
  71605. get: function () {
  71606. return this.onTriggerStateChangedObservable;
  71607. },
  71608. enumerable: true,
  71609. configurable: true
  71610. });
  71611. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71612. /**
  71613. * Fired when the menu button on this controller is modified
  71614. */
  71615. get: function () {
  71616. return this.onSecondaryButtonStateChangedObservable;
  71617. },
  71618. enumerable: true,
  71619. configurable: true
  71620. });
  71621. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71622. /**
  71623. * Fired when the grip button on this controller is modified
  71624. */
  71625. get: function () {
  71626. return this.onMainButtonStateChangedObservable;
  71627. },
  71628. enumerable: true,
  71629. configurable: true
  71630. });
  71631. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71632. /**
  71633. * Fired when the thumbstick button on this controller is modified
  71634. */
  71635. get: function () {
  71636. return this.onPadStateChangedObservable;
  71637. },
  71638. enumerable: true,
  71639. configurable: true
  71640. });
  71641. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71642. /**
  71643. * Fired when the touchpad button on this controller is modified
  71644. */
  71645. get: function () {
  71646. return this.onTrackpadChangedObservable;
  71647. },
  71648. enumerable: true,
  71649. configurable: true
  71650. });
  71651. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71652. /**
  71653. * Fired when the touchpad values on this controller are modified
  71654. */
  71655. get: function () {
  71656. return this.onTrackpadValuesChangedObservable;
  71657. },
  71658. enumerable: true,
  71659. configurable: true
  71660. });
  71661. /**
  71662. * Called once per frame by the engine.
  71663. */
  71664. WindowsMotionController.prototype.update = function () {
  71665. _super.prototype.update.call(this);
  71666. if (this.browserGamepad.axes) {
  71667. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71668. this.trackpad.x = this.browserGamepad["axes"][2];
  71669. this.trackpad.y = this.browserGamepad["axes"][3];
  71670. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71671. }
  71672. // Only need to animate axes if there is a loaded mesh
  71673. if (this._loadedMeshInfo) {
  71674. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71675. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71676. }
  71677. }
  71678. }
  71679. };
  71680. /**
  71681. * Called once for each button that changed state since the last frame
  71682. * @param buttonIdx Which button index changed
  71683. * @param state New state of the button
  71684. * @param changes Which properties on the state changed since last frame
  71685. */
  71686. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71687. var buttonName = this._mapping.buttons[buttonIdx];
  71688. if (!buttonName) {
  71689. return;
  71690. }
  71691. // Only emit events for buttons that we know how to map from index to name
  71692. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71693. if (observable) {
  71694. observable.notifyObservers(state);
  71695. }
  71696. this._lerpButtonTransform(buttonName, state.value);
  71697. };
  71698. /**
  71699. * Moves the buttons on the controller mesh based on their current state
  71700. * @param buttonName the name of the button to move
  71701. * @param buttonValue the value of the button which determines the buttons new position
  71702. */
  71703. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71704. // If there is no loaded mesh, there is nothing to transform.
  71705. if (!this._loadedMeshInfo) {
  71706. return;
  71707. }
  71708. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71709. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71710. return;
  71711. }
  71712. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71713. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71714. };
  71715. /**
  71716. * Moves the axis on the controller mesh based on its current state
  71717. * @param axis the index of the axis
  71718. * @param axisValue the value of the axis which determines the meshes new position
  71719. * @hidden
  71720. */
  71721. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71722. if (!this._loadedMeshInfo) {
  71723. return;
  71724. }
  71725. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71726. if (!meshInfo) {
  71727. return;
  71728. }
  71729. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71730. return;
  71731. }
  71732. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71733. var lerpValue = axisValue * 0.5 + 0.5;
  71734. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71735. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71736. };
  71737. /**
  71738. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71739. * @param scene scene in which to add meshes
  71740. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71741. */
  71742. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71743. var _this = this;
  71744. if (forceDefault === void 0) { forceDefault = false; }
  71745. var path;
  71746. var filename;
  71747. // Checking if GLB loader is present
  71748. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71749. // Determine the device specific folder based on the ID suffix
  71750. var device = 'default';
  71751. if (this.id && !forceDefault) {
  71752. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71753. device = ((match && match[0]) || device);
  71754. }
  71755. // Hand
  71756. if (this.hand === 'left') {
  71757. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71758. }
  71759. else { // Right is the default if no hand is specified
  71760. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71761. }
  71762. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71763. }
  71764. else {
  71765. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71766. path = BABYLON.GenericController.MODEL_BASE_URL;
  71767. filename = BABYLON.GenericController.MODEL_FILENAME;
  71768. }
  71769. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71770. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71771. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71772. if (!_this._loadedMeshInfo) {
  71773. return;
  71774. }
  71775. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71776. _this.attachToMesh(_this._defaultModel);
  71777. if (meshLoaded) {
  71778. meshLoaded(_this._defaultModel);
  71779. }
  71780. }, null, function (scene, message) {
  71781. BABYLON.Tools.Log(message);
  71782. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71783. if (!forceDefault) {
  71784. _this.initControllerMesh(scene, meshLoaded, true);
  71785. }
  71786. });
  71787. };
  71788. /**
  71789. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71790. * can be transformed by button presses and axes values, based on this._mapping.
  71791. *
  71792. * @param scene scene in which the meshes exist
  71793. * @param meshes list of meshes that make up the controller model to process
  71794. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71795. */
  71796. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71797. var loadedMeshInfo = null;
  71798. // Create a new mesh to contain the glTF hierarchy
  71799. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71800. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71801. var childMesh = null;
  71802. for (var i = 0; i < meshes.length; i++) {
  71803. var mesh = meshes[i];
  71804. if (!mesh.parent) {
  71805. // Exclude controller meshes from picking results
  71806. mesh.isPickable = false;
  71807. // Handle root node, attach to the new parentMesh
  71808. childMesh = mesh;
  71809. break;
  71810. }
  71811. }
  71812. if (childMesh) {
  71813. childMesh.setParent(parentMesh);
  71814. // Create our mesh info. Note that this method will always return non-null.
  71815. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71816. }
  71817. else {
  71818. BABYLON.Tools.Warn('Could not find root node in model file.');
  71819. }
  71820. return loadedMeshInfo;
  71821. };
  71822. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71823. var loadedMeshInfo = new LoadedMeshInfo();
  71824. var i;
  71825. loadedMeshInfo.rootNode = rootNode;
  71826. // Reset the caches
  71827. loadedMeshInfo.buttonMeshes = {};
  71828. loadedMeshInfo.axisMeshes = {};
  71829. // Button Meshes
  71830. for (i = 0; i < this._mapping.buttons.length; i++) {
  71831. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71832. if (!buttonMeshName) {
  71833. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71834. continue;
  71835. }
  71836. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71837. if (!buttonMesh) {
  71838. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71839. continue;
  71840. }
  71841. var buttonMeshInfo = {
  71842. index: i,
  71843. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71844. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71845. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71846. };
  71847. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71848. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71849. }
  71850. else {
  71851. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71852. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71853. '(VALUE: ' + !!buttonMeshInfo.value +
  71854. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71855. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71856. ')');
  71857. }
  71858. }
  71859. // Axis Meshes
  71860. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71861. var axisMeshName = this._mapping.axisMeshNames[i];
  71862. if (!axisMeshName) {
  71863. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71864. continue;
  71865. }
  71866. var axisMesh = getChildByName(rootNode, axisMeshName);
  71867. if (!axisMesh) {
  71868. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71869. continue;
  71870. }
  71871. var axisMeshInfo = {
  71872. index: i,
  71873. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71874. min: getImmediateChildByName(axisMesh, 'MIN'),
  71875. max: getImmediateChildByName(axisMesh, 'MAX')
  71876. };
  71877. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71878. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71879. }
  71880. else {
  71881. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71882. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71883. '(VALUE: ' + !!axisMeshInfo.value +
  71884. ', MIN: ' + !!axisMeshInfo.min +
  71885. ', MAX:' + !!axisMeshInfo.max +
  71886. ')');
  71887. }
  71888. }
  71889. // Pointing Ray
  71890. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71891. if (!loadedMeshInfo.pointingPoseNode) {
  71892. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71893. }
  71894. return loadedMeshInfo;
  71895. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71896. function getChildByName(node, name) {
  71897. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71898. }
  71899. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71900. function getImmediateChildByName(node, name) {
  71901. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71902. }
  71903. };
  71904. /**
  71905. * Gets the ray of the controller in the direction the controller is pointing
  71906. * @param length the length the resulting ray should be
  71907. * @returns a ray in the direction the controller is pointing
  71908. */
  71909. WindowsMotionController.prototype.getForwardRay = function (length) {
  71910. if (length === void 0) { length = 100; }
  71911. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71912. return _super.prototype.getForwardRay.call(this, length);
  71913. }
  71914. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71915. var origin = m.getTranslation();
  71916. var forward = new BABYLON.Vector3(0, 0, -1);
  71917. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71918. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71919. return new BABYLON.Ray(origin, direction, length);
  71920. };
  71921. /**
  71922. * Disposes of the controller
  71923. */
  71924. WindowsMotionController.prototype.dispose = function () {
  71925. _super.prototype.dispose.call(this);
  71926. this.onTrackpadChangedObservable.clear();
  71927. };
  71928. /**
  71929. * The base url used to load the left and right controller models
  71930. */
  71931. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71932. /**
  71933. * The name of the left controller model file
  71934. */
  71935. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71936. /**
  71937. * The name of the right controller model file
  71938. */
  71939. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71940. /**
  71941. * The controller name prefix for this controller type
  71942. */
  71943. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71944. /**
  71945. * The controller id pattern for this controller type
  71946. */
  71947. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71948. return WindowsMotionController;
  71949. }(BABYLON.WebVRController));
  71950. BABYLON.WindowsMotionController = WindowsMotionController;
  71951. })(BABYLON || (BABYLON = {}));
  71952. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71953. var BABYLON;
  71954. (function (BABYLON) {
  71955. /**
  71956. * Gear VR Controller
  71957. */
  71958. var GearVRController = /** @class */ (function (_super) {
  71959. __extends(GearVRController, _super);
  71960. /**
  71961. * Creates a new GearVRController from a gamepad
  71962. * @param vrGamepad the gamepad that the controller should be created from
  71963. */
  71964. function GearVRController(vrGamepad) {
  71965. var _this = _super.call(this, vrGamepad) || this;
  71966. _this._buttonIndexToObservableNameMap = [
  71967. 'onTrackpadChangedObservable',
  71968. 'onTriggerStateChangedObservable' // Trigger
  71969. ];
  71970. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71971. return _this;
  71972. }
  71973. /**
  71974. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71975. * @param scene scene in which to add meshes
  71976. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71977. */
  71978. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71979. var _this = this;
  71980. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71981. _this._defaultModel = newMeshes[1];
  71982. _this.attachToMesh(_this._defaultModel);
  71983. if (meshLoaded) {
  71984. meshLoaded(_this._defaultModel);
  71985. }
  71986. });
  71987. };
  71988. /**
  71989. * Called once for each button that changed state since the last frame
  71990. * @param buttonIdx Which button index changed
  71991. * @param state New state of the button
  71992. * @param changes Which properties on the state changed since last frame
  71993. */
  71994. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71995. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71996. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71997. // Only emit events for buttons that we know how to map from index to observable
  71998. var observable = this[observableName];
  71999. if (observable) {
  72000. observable.notifyObservers(state);
  72001. }
  72002. }
  72003. };
  72004. /**
  72005. * Base Url for the controller model.
  72006. */
  72007. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72008. /**
  72009. * File name for the controller model.
  72010. */
  72011. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72012. /**
  72013. * Gamepad Id prefix used to identify this controller.
  72014. */
  72015. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72016. return GearVRController;
  72017. }(BABYLON.WebVRController));
  72018. BABYLON.GearVRController = GearVRController;
  72019. })(BABYLON || (BABYLON = {}));
  72020. //# sourceMappingURL=babylon.gearVRController.js.map
  72021. var BABYLON;
  72022. (function (BABYLON) {
  72023. /**
  72024. * Google Daydream controller
  72025. */
  72026. var DaydreamController = /** @class */ (function (_super) {
  72027. __extends(DaydreamController, _super);
  72028. /**
  72029. * Creates a new DaydreamController from a gamepad
  72030. * @param vrGamepad the gamepad that the controller should be created from
  72031. */
  72032. function DaydreamController(vrGamepad) {
  72033. var _this = _super.call(this, vrGamepad) || this;
  72034. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72035. return _this;
  72036. }
  72037. /**
  72038. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72039. * @param scene scene in which to add meshes
  72040. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72041. */
  72042. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72043. var _this = this;
  72044. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72045. _this._defaultModel = newMeshes[1];
  72046. _this.attachToMesh(_this._defaultModel);
  72047. if (meshLoaded) {
  72048. meshLoaded(_this._defaultModel);
  72049. }
  72050. });
  72051. };
  72052. /**
  72053. * Called once for each button that changed state since the last frame
  72054. * @param buttonIdx Which button index changed
  72055. * @param state New state of the button
  72056. * @param changes Which properties on the state changed since last frame
  72057. */
  72058. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72059. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72060. if (buttonIdx === 0) {
  72061. var observable = this.onTriggerStateChangedObservable;
  72062. if (observable) {
  72063. observable.notifyObservers(state);
  72064. }
  72065. }
  72066. else {
  72067. // If the app or home buttons are ever made available
  72068. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72069. }
  72070. };
  72071. /**
  72072. * Base Url for the controller model.
  72073. */
  72074. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72075. /**
  72076. * File name for the controller model.
  72077. */
  72078. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72079. /**
  72080. * Gamepad Id prefix used to identify Daydream Controller.
  72081. */
  72082. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72083. return DaydreamController;
  72084. }(BABYLON.WebVRController));
  72085. BABYLON.DaydreamController = DaydreamController;
  72086. })(BABYLON || (BABYLON = {}));
  72087. //# sourceMappingURL=babylon.daydreamController.js.map
  72088. var BABYLON;
  72089. (function (BABYLON) {
  72090. var FollowCamera = /** @class */ (function (_super) {
  72091. __extends(FollowCamera, _super);
  72092. function FollowCamera(name, position, scene, lockedTarget) {
  72093. if (lockedTarget === void 0) { lockedTarget = null; }
  72094. var _this = _super.call(this, name, position, scene) || this;
  72095. _this.radius = 12;
  72096. _this.rotationOffset = 0;
  72097. _this.heightOffset = 4;
  72098. _this.cameraAcceleration = 0.05;
  72099. _this.maxCameraSpeed = 20;
  72100. _this.lockedTarget = lockedTarget;
  72101. return _this;
  72102. }
  72103. FollowCamera.prototype.getRadians = function (degrees) {
  72104. return degrees * Math.PI / 180;
  72105. };
  72106. FollowCamera.prototype.follow = function (cameraTarget) {
  72107. if (!cameraTarget)
  72108. return;
  72109. var yRotation;
  72110. if (cameraTarget.rotationQuaternion) {
  72111. var rotMatrix = new BABYLON.Matrix();
  72112. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72113. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72114. }
  72115. else {
  72116. yRotation = cameraTarget.rotation.y;
  72117. }
  72118. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72119. var targetPosition = cameraTarget.getAbsolutePosition();
  72120. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72121. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72122. var dx = targetX - this.position.x;
  72123. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72124. var dz = (targetZ) - this.position.z;
  72125. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72126. var vy = dy * this.cameraAcceleration;
  72127. var vz = dz * this.cameraAcceleration * 2;
  72128. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72129. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72130. }
  72131. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72132. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72133. }
  72134. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72135. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72136. }
  72137. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72138. this.setTarget(targetPosition);
  72139. };
  72140. FollowCamera.prototype._checkInputs = function () {
  72141. _super.prototype._checkInputs.call(this);
  72142. if (this.lockedTarget) {
  72143. this.follow(this.lockedTarget);
  72144. }
  72145. };
  72146. FollowCamera.prototype.getClassName = function () {
  72147. return "FollowCamera";
  72148. };
  72149. __decorate([
  72150. BABYLON.serialize()
  72151. ], FollowCamera.prototype, "radius", void 0);
  72152. __decorate([
  72153. BABYLON.serialize()
  72154. ], FollowCamera.prototype, "rotationOffset", void 0);
  72155. __decorate([
  72156. BABYLON.serialize()
  72157. ], FollowCamera.prototype, "heightOffset", void 0);
  72158. __decorate([
  72159. BABYLON.serialize()
  72160. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72161. __decorate([
  72162. BABYLON.serialize()
  72163. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72164. __decorate([
  72165. BABYLON.serializeAsMeshReference("lockedTargetId")
  72166. ], FollowCamera.prototype, "lockedTarget", void 0);
  72167. return FollowCamera;
  72168. }(BABYLON.TargetCamera));
  72169. BABYLON.FollowCamera = FollowCamera;
  72170. var ArcFollowCamera = /** @class */ (function (_super) {
  72171. __extends(ArcFollowCamera, _super);
  72172. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72173. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72174. _this.alpha = alpha;
  72175. _this.beta = beta;
  72176. _this.radius = radius;
  72177. _this.target = target;
  72178. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72179. _this.follow();
  72180. return _this;
  72181. }
  72182. ArcFollowCamera.prototype.follow = function () {
  72183. if (!this.target) {
  72184. return;
  72185. }
  72186. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72187. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72188. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72189. var targetPosition = this.target.getAbsolutePosition();
  72190. this.position = targetPosition.add(this._cartesianCoordinates);
  72191. this.setTarget(targetPosition);
  72192. };
  72193. ArcFollowCamera.prototype._checkInputs = function () {
  72194. _super.prototype._checkInputs.call(this);
  72195. this.follow();
  72196. };
  72197. ArcFollowCamera.prototype.getClassName = function () {
  72198. return "ArcFollowCamera";
  72199. };
  72200. return ArcFollowCamera;
  72201. }(BABYLON.TargetCamera));
  72202. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72203. })(BABYLON || (BABYLON = {}));
  72204. //# sourceMappingURL=babylon.followCamera.js.map
  72205. var BABYLON;
  72206. (function (BABYLON) {
  72207. // We're mainly based on the logic defined into the FreeCamera code
  72208. var UniversalCamera = /** @class */ (function (_super) {
  72209. __extends(UniversalCamera, _super);
  72210. //-- end properties for backward compatibility for inputs
  72211. function UniversalCamera(name, position, scene) {
  72212. var _this = _super.call(this, name, position, scene) || this;
  72213. _this.inputs.addGamepad();
  72214. return _this;
  72215. }
  72216. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72217. //-- Begin properties for backward compatibility for inputs
  72218. get: function () {
  72219. var gamepad = this.inputs.attached["gamepad"];
  72220. if (gamepad)
  72221. return gamepad.gamepadAngularSensibility;
  72222. return 0;
  72223. },
  72224. set: function (value) {
  72225. var gamepad = this.inputs.attached["gamepad"];
  72226. if (gamepad)
  72227. gamepad.gamepadAngularSensibility = value;
  72228. },
  72229. enumerable: true,
  72230. configurable: true
  72231. });
  72232. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72233. get: function () {
  72234. var gamepad = this.inputs.attached["gamepad"];
  72235. if (gamepad)
  72236. return gamepad.gamepadMoveSensibility;
  72237. return 0;
  72238. },
  72239. set: function (value) {
  72240. var gamepad = this.inputs.attached["gamepad"];
  72241. if (gamepad)
  72242. gamepad.gamepadMoveSensibility = value;
  72243. },
  72244. enumerable: true,
  72245. configurable: true
  72246. });
  72247. UniversalCamera.prototype.getClassName = function () {
  72248. return "UniversalCamera";
  72249. };
  72250. return UniversalCamera;
  72251. }(BABYLON.TouchCamera));
  72252. BABYLON.UniversalCamera = UniversalCamera;
  72253. })(BABYLON || (BABYLON = {}));
  72254. //# sourceMappingURL=babylon.universalCamera.js.map
  72255. var BABYLON;
  72256. (function (BABYLON) {
  72257. // We're mainly based on the logic defined into the FreeCamera code
  72258. var GamepadCamera = /** @class */ (function (_super) {
  72259. __extends(GamepadCamera, _super);
  72260. //-- end properties for backward compatibility for inputs
  72261. function GamepadCamera(name, position, scene) {
  72262. return _super.call(this, name, position, scene) || this;
  72263. }
  72264. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72265. //-- Begin properties for backward compatibility for inputs
  72266. get: function () {
  72267. var gamepad = this.inputs.attached["gamepad"];
  72268. if (gamepad)
  72269. return gamepad.gamepadAngularSensibility;
  72270. return 0;
  72271. },
  72272. set: function (value) {
  72273. var gamepad = this.inputs.attached["gamepad"];
  72274. if (gamepad)
  72275. gamepad.gamepadAngularSensibility = value;
  72276. },
  72277. enumerable: true,
  72278. configurable: true
  72279. });
  72280. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72281. get: function () {
  72282. var gamepad = this.inputs.attached["gamepad"];
  72283. if (gamepad)
  72284. return gamepad.gamepadMoveSensibility;
  72285. return 0;
  72286. },
  72287. set: function (value) {
  72288. var gamepad = this.inputs.attached["gamepad"];
  72289. if (gamepad)
  72290. gamepad.gamepadMoveSensibility = value;
  72291. },
  72292. enumerable: true,
  72293. configurable: true
  72294. });
  72295. GamepadCamera.prototype.getClassName = function () {
  72296. return "GamepadCamera";
  72297. };
  72298. return GamepadCamera;
  72299. }(BABYLON.UniversalCamera));
  72300. BABYLON.GamepadCamera = GamepadCamera;
  72301. })(BABYLON || (BABYLON = {}));
  72302. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72303. var BABYLON;
  72304. (function (BABYLON) {
  72305. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72306. function PostProcessRenderPipelineManager() {
  72307. this._renderPipelines = {};
  72308. }
  72309. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72310. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72311. };
  72312. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72313. if (unique === void 0) { unique = false; }
  72314. var renderPipeline = this._renderPipelines[renderPipelineName];
  72315. if (!renderPipeline) {
  72316. return;
  72317. }
  72318. renderPipeline._attachCameras(cameras, unique);
  72319. };
  72320. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72321. var renderPipeline = this._renderPipelines[renderPipelineName];
  72322. if (!renderPipeline) {
  72323. return;
  72324. }
  72325. renderPipeline._detachCameras(cameras);
  72326. };
  72327. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72328. var renderPipeline = this._renderPipelines[renderPipelineName];
  72329. if (!renderPipeline) {
  72330. return;
  72331. }
  72332. renderPipeline._enableEffect(renderEffectName, cameras);
  72333. };
  72334. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72335. var renderPipeline = this._renderPipelines[renderPipelineName];
  72336. if (!renderPipeline) {
  72337. return;
  72338. }
  72339. renderPipeline._disableEffect(renderEffectName, cameras);
  72340. };
  72341. PostProcessRenderPipelineManager.prototype.update = function () {
  72342. for (var renderPipelineName in this._renderPipelines) {
  72343. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72344. var pipeline = this._renderPipelines[renderPipelineName];
  72345. if (!pipeline.isSupported) {
  72346. pipeline.dispose();
  72347. delete this._renderPipelines[renderPipelineName];
  72348. }
  72349. else {
  72350. pipeline._update();
  72351. }
  72352. }
  72353. }
  72354. };
  72355. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72356. for (var renderPipelineName in this._renderPipelines) {
  72357. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72358. var pipeline = this._renderPipelines[renderPipelineName];
  72359. pipeline._rebuild();
  72360. }
  72361. }
  72362. };
  72363. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72364. for (var renderPipelineName in this._renderPipelines) {
  72365. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72366. var pipeline = this._renderPipelines[renderPipelineName];
  72367. pipeline.dispose();
  72368. }
  72369. }
  72370. };
  72371. return PostProcessRenderPipelineManager;
  72372. }());
  72373. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72374. })(BABYLON || (BABYLON = {}));
  72375. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72376. var BABYLON;
  72377. (function (BABYLON) {
  72378. /**
  72379. * This represents a set of one or more post processes in Babylon.
  72380. * A post process can be used to apply a shader to a texture after it is rendered.
  72381. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72382. */
  72383. var PostProcessRenderEffect = /** @class */ (function () {
  72384. /**
  72385. * Instantiates a post process render effect.
  72386. * A post process can be used to apply a shader to a texture after it is rendered.
  72387. * @param engine The engine the effect is tied to
  72388. * @param name The name of the effect
  72389. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72390. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72391. */
  72392. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72393. this._name = name;
  72394. this._singleInstance = singleInstance || true;
  72395. this._getPostProcesses = getPostProcesses;
  72396. this._cameras = {};
  72397. this._indicesForCamera = {};
  72398. this._postProcesses = {};
  72399. }
  72400. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72401. /**
  72402. * Checks if all the post processes in the effect are supported.
  72403. */
  72404. get: function () {
  72405. for (var index in this._postProcesses) {
  72406. if (this._postProcesses.hasOwnProperty(index)) {
  72407. var pps = this._postProcesses[index];
  72408. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72409. if (!pps[ppIndex].isSupported) {
  72410. return false;
  72411. }
  72412. }
  72413. }
  72414. }
  72415. return true;
  72416. },
  72417. enumerable: true,
  72418. configurable: true
  72419. });
  72420. /**
  72421. * Updates the current state of the effect
  72422. */
  72423. PostProcessRenderEffect.prototype._update = function () {
  72424. };
  72425. /**
  72426. * Attaches the effect on cameras
  72427. * @param cameras The camera to attach to.
  72428. */
  72429. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72430. var _this = this;
  72431. var cameraKey;
  72432. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72433. if (!cams) {
  72434. return;
  72435. }
  72436. for (var i = 0; i < cams.length; i++) {
  72437. var camera = cams[i];
  72438. var cameraName = camera.name;
  72439. if (this._singleInstance) {
  72440. cameraKey = 0;
  72441. }
  72442. else {
  72443. cameraKey = cameraName;
  72444. }
  72445. if (!this._postProcesses[cameraKey]) {
  72446. var postProcess = this._getPostProcesses();
  72447. if (postProcess) {
  72448. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72449. }
  72450. }
  72451. if (!this._indicesForCamera[cameraName]) {
  72452. this._indicesForCamera[cameraName] = [];
  72453. }
  72454. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72455. var index = camera.attachPostProcess(postProcess);
  72456. _this._indicesForCamera[cameraName].push(index);
  72457. });
  72458. if (!this._cameras[cameraName]) {
  72459. this._cameras[cameraName] = camera;
  72460. }
  72461. }
  72462. };
  72463. /**
  72464. * Detatches the effect on cameras
  72465. * @param cameras The camera to detatch from.
  72466. */
  72467. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72468. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72469. if (!cams) {
  72470. return;
  72471. }
  72472. for (var i = 0; i < cams.length; i++) {
  72473. var camera = cams[i];
  72474. var cameraName = camera.name;
  72475. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72476. camera.detachPostProcess(postProcess);
  72477. });
  72478. if (this._cameras[cameraName]) {
  72479. //this._indicesForCamera.splice(index, 1);
  72480. this._cameras[cameraName] = null;
  72481. }
  72482. }
  72483. };
  72484. /**
  72485. * Enables the effect on given cameras
  72486. * @param cameras The camera to enable.
  72487. */
  72488. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72489. var _this = this;
  72490. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72491. if (!cams) {
  72492. return;
  72493. }
  72494. for (var i = 0; i < cams.length; i++) {
  72495. var camera = cams[i];
  72496. var cameraName = camera.name;
  72497. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72498. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72499. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72500. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72501. });
  72502. }
  72503. }
  72504. }
  72505. };
  72506. /**
  72507. * Disables the effect on the given cameras
  72508. * @param cameras The camera to disable.
  72509. */
  72510. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72511. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72512. if (!cams) {
  72513. return;
  72514. }
  72515. for (var i = 0; i < cams.length; i++) {
  72516. var camera = cams[i];
  72517. var cameraName = camera.name;
  72518. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72519. camera.detachPostProcess(postProcess);
  72520. });
  72521. }
  72522. };
  72523. /**
  72524. * Gets a list of the post processes contained in the effect.
  72525. * @param camera The camera to get the post processes on.
  72526. * @returns The list of the post processes in the effect.
  72527. */
  72528. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72529. if (this._singleInstance) {
  72530. return this._postProcesses[0];
  72531. }
  72532. else {
  72533. if (!camera) {
  72534. return null;
  72535. }
  72536. return this._postProcesses[camera.name];
  72537. }
  72538. };
  72539. return PostProcessRenderEffect;
  72540. }());
  72541. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72542. })(BABYLON || (BABYLON = {}));
  72543. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72544. var BABYLON;
  72545. (function (BABYLON) {
  72546. var PostProcessRenderPipeline = /** @class */ (function () {
  72547. function PostProcessRenderPipeline(engine, name) {
  72548. this.engine = engine;
  72549. this._name = name;
  72550. this._renderEffects = {};
  72551. this._renderEffectsForIsolatedPass = new Array();
  72552. this._cameras = [];
  72553. }
  72554. PostProcessRenderPipeline.prototype.getClassName = function () {
  72555. return "PostProcessRenderPipeline";
  72556. };
  72557. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72558. get: function () {
  72559. for (var renderEffectName in this._renderEffects) {
  72560. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72561. if (!this._renderEffects[renderEffectName].isSupported) {
  72562. return false;
  72563. }
  72564. }
  72565. }
  72566. return true;
  72567. },
  72568. enumerable: true,
  72569. configurable: true
  72570. });
  72571. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72572. this._renderEffects[renderEffect._name] = renderEffect;
  72573. };
  72574. // private
  72575. PostProcessRenderPipeline.prototype._rebuild = function () {
  72576. };
  72577. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72578. var renderEffects = this._renderEffects[renderEffectName];
  72579. if (!renderEffects) {
  72580. return;
  72581. }
  72582. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72583. };
  72584. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72585. var renderEffects = this._renderEffects[renderEffectName];
  72586. if (!renderEffects) {
  72587. return;
  72588. }
  72589. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72590. };
  72591. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72592. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72593. if (!cams) {
  72594. return;
  72595. }
  72596. var indicesToDelete = [];
  72597. var i;
  72598. for (i = 0; i < cams.length; i++) {
  72599. var camera = cams[i];
  72600. var cameraName = camera.name;
  72601. if (this._cameras.indexOf(camera) === -1) {
  72602. this._cameras[cameraName] = camera;
  72603. }
  72604. else if (unique) {
  72605. indicesToDelete.push(i);
  72606. }
  72607. }
  72608. for (i = 0; i < indicesToDelete.length; i++) {
  72609. cameras.splice(indicesToDelete[i], 1);
  72610. }
  72611. for (var renderEffectName in this._renderEffects) {
  72612. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72613. this._renderEffects[renderEffectName]._attachCameras(cams);
  72614. }
  72615. }
  72616. };
  72617. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72618. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72619. if (!cams) {
  72620. return;
  72621. }
  72622. for (var renderEffectName in this._renderEffects) {
  72623. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72624. this._renderEffects[renderEffectName]._detachCameras(cams);
  72625. }
  72626. }
  72627. for (var i = 0; i < cams.length; i++) {
  72628. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72629. }
  72630. };
  72631. PostProcessRenderPipeline.prototype._update = function () {
  72632. for (var renderEffectName in this._renderEffects) {
  72633. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72634. this._renderEffects[renderEffectName]._update();
  72635. }
  72636. }
  72637. for (var i = 0; i < this._cameras.length; i++) {
  72638. var cameraName = this._cameras[i].name;
  72639. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72640. this._renderEffectsForIsolatedPass[cameraName]._update();
  72641. }
  72642. }
  72643. };
  72644. PostProcessRenderPipeline.prototype._reset = function () {
  72645. this._renderEffects = {};
  72646. this._renderEffectsForIsolatedPass = new Array();
  72647. };
  72648. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72649. // 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)
  72650. var effectKeys = Object.keys(this._renderEffects);
  72651. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72652. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72653. if (postProcesses) {
  72654. postProcesses[0].samples = sampleCount;
  72655. return true;
  72656. }
  72657. }
  72658. return false;
  72659. };
  72660. PostProcessRenderPipeline.prototype.dispose = function () {
  72661. // Must be implemented by children
  72662. };
  72663. __decorate([
  72664. BABYLON.serialize()
  72665. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72666. return PostProcessRenderPipeline;
  72667. }());
  72668. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72669. })(BABYLON || (BABYLON = {}));
  72670. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72671. var BABYLON;
  72672. (function (BABYLON) {
  72673. /**
  72674. * This represents a depth renderer in Babylon.
  72675. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72676. */
  72677. var DepthRenderer = /** @class */ (function () {
  72678. /**
  72679. * Instantiates a depth renderer
  72680. * @param scene The scene the renderer belongs to
  72681. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72682. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72683. */
  72684. function DepthRenderer(scene, type, camera) {
  72685. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72686. if (camera === void 0) { camera = null; }
  72687. var _this = this;
  72688. this._scene = scene;
  72689. this._camera = camera;
  72690. var engine = scene.getEngine();
  72691. // Render target
  72692. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72693. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72694. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72695. this._depthMap.refreshRate = 1;
  72696. this._depthMap.renderParticles = false;
  72697. this._depthMap.renderList = null;
  72698. // Camera to get depth map from to support multiple concurrent cameras
  72699. this._depthMap.activeCamera = this._camera;
  72700. this._depthMap.ignoreCameraViewport = true;
  72701. this._depthMap.useCameraPostProcesses = false;
  72702. // set default depth value to 1.0 (far away)
  72703. this._depthMap.onClearObservable.add(function (engine) {
  72704. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72705. });
  72706. // Custom render function
  72707. var renderSubMesh = function (subMesh) {
  72708. var mesh = subMesh.getRenderingMesh();
  72709. var scene = _this._scene;
  72710. var engine = scene.getEngine();
  72711. var material = subMesh.getMaterial();
  72712. if (!material) {
  72713. return;
  72714. }
  72715. // Culling and reverse (right handed system)
  72716. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72717. // Managing instances
  72718. var batch = mesh._getInstancesRenderList(subMesh._id);
  72719. if (batch.mustReturn) {
  72720. return;
  72721. }
  72722. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72723. var camera = _this._camera || scene.activeCamera;
  72724. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72725. engine.enableEffect(_this._effect);
  72726. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72727. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72728. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72729. // Alpha test
  72730. if (material && material.needAlphaTesting()) {
  72731. var alphaTexture = material.getAlphaTestTexture();
  72732. if (alphaTexture) {
  72733. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72734. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72735. }
  72736. }
  72737. // Bones
  72738. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72739. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72740. }
  72741. // Draw
  72742. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72743. }
  72744. };
  72745. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72746. var index;
  72747. if (depthOnlySubMeshes.length) {
  72748. engine.setColorWrite(false);
  72749. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72750. renderSubMesh(depthOnlySubMeshes.data[index]);
  72751. }
  72752. engine.setColorWrite(true);
  72753. }
  72754. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72755. renderSubMesh(opaqueSubMeshes.data[index]);
  72756. }
  72757. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72758. renderSubMesh(alphaTestSubMeshes.data[index]);
  72759. }
  72760. };
  72761. }
  72762. /**
  72763. * Creates the depth rendering effect and checks if the effect is ready.
  72764. * @param subMesh The submesh to be used to render the depth map of
  72765. * @param useInstances If multiple world instances should be used
  72766. * @returns if the depth renderer is ready to render the depth map
  72767. */
  72768. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72769. var material = subMesh.getMaterial();
  72770. if (material.disableDepthWrite) {
  72771. return false;
  72772. }
  72773. var defines = [];
  72774. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72775. var mesh = subMesh.getMesh();
  72776. // Alpha test
  72777. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72778. defines.push("#define ALPHATEST");
  72779. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72780. attribs.push(BABYLON.VertexBuffer.UVKind);
  72781. defines.push("#define UV1");
  72782. }
  72783. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72784. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72785. defines.push("#define UV2");
  72786. }
  72787. }
  72788. // Bones
  72789. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72790. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72791. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72792. if (mesh.numBoneInfluencers > 4) {
  72793. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72794. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72795. }
  72796. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72797. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72798. }
  72799. else {
  72800. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72801. }
  72802. // Instances
  72803. if (useInstances) {
  72804. defines.push("#define INSTANCES");
  72805. attribs.push("world0");
  72806. attribs.push("world1");
  72807. attribs.push("world2");
  72808. attribs.push("world3");
  72809. }
  72810. // Get correct effect
  72811. var join = defines.join("\n");
  72812. if (this._cachedDefines !== join) {
  72813. this._cachedDefines = join;
  72814. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72815. }
  72816. return this._effect.isReady();
  72817. };
  72818. /**
  72819. * Gets the texture which the depth map will be written to.
  72820. * @returns The depth map texture
  72821. */
  72822. DepthRenderer.prototype.getDepthMap = function () {
  72823. return this._depthMap;
  72824. };
  72825. /**
  72826. * Disposes of the depth renderer.
  72827. */
  72828. DepthRenderer.prototype.dispose = function () {
  72829. this._depthMap.dispose();
  72830. };
  72831. return DepthRenderer;
  72832. }());
  72833. BABYLON.DepthRenderer = DepthRenderer;
  72834. })(BABYLON || (BABYLON = {}));
  72835. //# sourceMappingURL=babylon.depthRenderer.js.map
  72836. var BABYLON;
  72837. (function (BABYLON) {
  72838. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72839. __extends(SSAORenderingPipeline, _super);
  72840. /**
  72841. * @constructor
  72842. * @param {string} name - The rendering pipeline name
  72843. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72844. * @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 }
  72845. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72846. */
  72847. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72848. var _this = _super.call(this, scene.getEngine(), name) || this;
  72849. // Members
  72850. /**
  72851. * The PassPostProcess id in the pipeline that contains the original scene color
  72852. */
  72853. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72854. /**
  72855. * The SSAO PostProcess id in the pipeline
  72856. */
  72857. _this.SSAORenderEffect = "SSAORenderEffect";
  72858. /**
  72859. * The horizontal blur PostProcess id in the pipeline
  72860. */
  72861. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72862. /**
  72863. * The vertical blur PostProcess id in the pipeline
  72864. */
  72865. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72866. /**
  72867. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72868. */
  72869. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72870. /**
  72871. * The output strength of the SSAO post-process. Default value is 1.0.
  72872. */
  72873. _this.totalStrength = 1.0;
  72874. /**
  72875. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72876. */
  72877. _this.radius = 0.0001;
  72878. /**
  72879. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72880. * Must not be equal to fallOff and superior to fallOff.
  72881. * Default value is 0.975
  72882. */
  72883. _this.area = 0.0075;
  72884. /**
  72885. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72886. * Must not be equal to area and inferior to area.
  72887. * Default value is 0.0
  72888. */
  72889. _this.fallOff = 0.000001;
  72890. /**
  72891. * The base color of the SSAO post-process
  72892. * The final result is "base + ssao" between [0, 1]
  72893. */
  72894. _this.base = 0.5;
  72895. _this._firstUpdate = true;
  72896. _this._scene = scene;
  72897. // Set up assets
  72898. _this._createRandomTexture();
  72899. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72900. var ssaoRatio = ratio.ssaoRatio || ratio;
  72901. var combineRatio = ratio.combineRatio || ratio;
  72902. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72903. _this._createSSAOPostProcess(ssaoRatio);
  72904. _this._createBlurPostProcess(ssaoRatio);
  72905. _this._createSSAOCombinePostProcess(combineRatio);
  72906. // Set up pipeline
  72907. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72908. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72909. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72910. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72911. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72912. // Finish
  72913. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72914. if (cameras)
  72915. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72916. return _this;
  72917. }
  72918. // Public Methods
  72919. /**
  72920. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72921. */
  72922. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72923. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72924. for (var i = 0; i < this._scene.cameras.length; i++) {
  72925. var camera = this._scene.cameras[i];
  72926. this._originalColorPostProcess.dispose(camera);
  72927. this._ssaoPostProcess.dispose(camera);
  72928. this._blurHPostProcess.dispose(camera);
  72929. this._blurVPostProcess.dispose(camera);
  72930. this._ssaoCombinePostProcess.dispose(camera);
  72931. }
  72932. this._randomTexture.dispose();
  72933. if (disableDepthRender)
  72934. this._scene.disableDepthRenderer();
  72935. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72936. _super.prototype.dispose.call(this);
  72937. };
  72938. // Private Methods
  72939. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72940. var _this = this;
  72941. var size = 16;
  72942. 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);
  72943. 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);
  72944. this._blurHPostProcess.onActivateObservable.add(function () {
  72945. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72946. _this._blurHPostProcess.kernel = size * dw;
  72947. });
  72948. this._blurVPostProcess.onActivateObservable.add(function () {
  72949. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72950. _this._blurVPostProcess.kernel = size * dw;
  72951. });
  72952. };
  72953. SSAORenderingPipeline.prototype._rebuild = function () {
  72954. this._firstUpdate = true;
  72955. _super.prototype._rebuild.call(this);
  72956. };
  72957. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72958. var _this = this;
  72959. var numSamples = 16;
  72960. var sampleSphere = [
  72961. 0.5381, 0.1856, -0.4319,
  72962. 0.1379, 0.2486, 0.4430,
  72963. 0.3371, 0.5679, -0.0057,
  72964. -0.6999, -0.0451, -0.0019,
  72965. 0.0689, -0.1598, -0.8547,
  72966. 0.0560, 0.0069, -0.1843,
  72967. -0.0146, 0.1402, 0.0762,
  72968. 0.0100, -0.1924, -0.0344,
  72969. -0.3577, -0.5301, -0.4358,
  72970. -0.3169, 0.1063, 0.0158,
  72971. 0.0103, -0.5869, 0.0046,
  72972. -0.0897, -0.4940, 0.3287,
  72973. 0.7119, -0.0154, -0.0918,
  72974. -0.0533, 0.0596, -0.5411,
  72975. 0.0352, -0.0631, 0.5460,
  72976. -0.4776, 0.2847, -0.0271
  72977. ];
  72978. var samplesFactor = 1.0 / numSamples;
  72979. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72980. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72981. "area", "fallOff", "base", "range", "viewport"
  72982. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72983. this._ssaoPostProcess.onApply = function (effect) {
  72984. if (_this._firstUpdate) {
  72985. effect.setArray3("sampleSphere", sampleSphere);
  72986. effect.setFloat("samplesFactor", samplesFactor);
  72987. effect.setFloat("randTextureTiles", 4.0);
  72988. }
  72989. effect.setFloat("totalStrength", _this.totalStrength);
  72990. effect.setFloat("radius", _this.radius);
  72991. effect.setFloat("area", _this.area);
  72992. effect.setFloat("fallOff", _this.fallOff);
  72993. effect.setFloat("base", _this.base);
  72994. effect.setTexture("textureSampler", _this._depthTexture);
  72995. effect.setTexture("randomSampler", _this._randomTexture);
  72996. };
  72997. };
  72998. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72999. var _this = this;
  73000. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73001. this._ssaoCombinePostProcess.onApply = function (effect) {
  73002. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73003. };
  73004. };
  73005. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73006. var size = 512;
  73007. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73008. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73009. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73010. var context = this._randomTexture.getContext();
  73011. var rand = function (min, max) {
  73012. return Math.random() * (max - min) + min;
  73013. };
  73014. var randVector = BABYLON.Vector3.Zero();
  73015. for (var x = 0; x < size; x++) {
  73016. for (var y = 0; y < size; y++) {
  73017. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73018. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73019. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73020. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73021. context.fillRect(x, y, 1, 1);
  73022. }
  73023. }
  73024. this._randomTexture.update(false);
  73025. };
  73026. __decorate([
  73027. BABYLON.serialize()
  73028. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73029. __decorate([
  73030. BABYLON.serialize()
  73031. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73032. __decorate([
  73033. BABYLON.serialize()
  73034. ], SSAORenderingPipeline.prototype, "area", void 0);
  73035. __decorate([
  73036. BABYLON.serialize()
  73037. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73038. __decorate([
  73039. BABYLON.serialize()
  73040. ], SSAORenderingPipeline.prototype, "base", void 0);
  73041. return SSAORenderingPipeline;
  73042. }(BABYLON.PostProcessRenderPipeline));
  73043. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73044. })(BABYLON || (BABYLON = {}));
  73045. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73046. var BABYLON;
  73047. (function (BABYLON) {
  73048. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73049. __extends(SSAO2RenderingPipeline, _super);
  73050. /**
  73051. * @constructor
  73052. * @param {string} name - The rendering pipeline name
  73053. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73054. * @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 }
  73055. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73056. */
  73057. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73058. var _this = _super.call(this, scene.getEngine(), name) || this;
  73059. // Members
  73060. /**
  73061. * The PassPostProcess id in the pipeline that contains the original scene color
  73062. */
  73063. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73064. /**
  73065. * The SSAO PostProcess id in the pipeline
  73066. */
  73067. _this.SSAORenderEffect = "SSAORenderEffect";
  73068. /**
  73069. * The horizontal blur PostProcess id in the pipeline
  73070. */
  73071. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73072. /**
  73073. * The vertical blur PostProcess id in the pipeline
  73074. */
  73075. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73076. /**
  73077. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73078. */
  73079. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73080. /**
  73081. * The output strength of the SSAO post-process. Default value is 1.0.
  73082. */
  73083. _this.totalStrength = 1.0;
  73084. /**
  73085. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73086. */
  73087. _this.maxZ = 100.0;
  73088. /**
  73089. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73090. */
  73091. _this.minZAspect = 0.2;
  73092. /**
  73093. * Number of samples used for the SSAO calculations. Default value is 8
  73094. */
  73095. _this._samples = 8;
  73096. /**
  73097. * Are we using bilateral blur ?
  73098. */
  73099. _this._expensiveBlur = true;
  73100. /**
  73101. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73102. */
  73103. _this.radius = 2.0;
  73104. /**
  73105. * The base color of the SSAO post-process
  73106. * The final result is "base + ssao" between [0, 1]
  73107. */
  73108. _this.base = 0.1;
  73109. _this._firstUpdate = true;
  73110. _this._scene = scene;
  73111. _this._ratio = ratio;
  73112. if (!_this.isSupported) {
  73113. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73114. return _this;
  73115. }
  73116. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73117. var blurRatio = _this._ratio.blurRatio || ratio;
  73118. // Set up assets
  73119. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73120. _this._createRandomTexture();
  73121. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73122. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73123. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73124. _this._createSSAOPostProcess(1.0);
  73125. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73126. _this._createSSAOCombinePostProcess(blurRatio);
  73127. // Set up pipeline
  73128. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73129. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73130. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73131. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73132. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73133. // Finish
  73134. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73135. if (cameras)
  73136. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73137. return _this;
  73138. }
  73139. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73140. get: function () {
  73141. return this._samples;
  73142. },
  73143. set: function (n) {
  73144. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73145. this._samples = n;
  73146. this._sampleSphere = this._generateHemisphere();
  73147. this._firstUpdate = true;
  73148. },
  73149. enumerable: true,
  73150. configurable: true
  73151. });
  73152. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73153. get: function () {
  73154. return this._expensiveBlur;
  73155. },
  73156. set: function (b) {
  73157. 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"]);
  73158. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73159. this._expensiveBlur = b;
  73160. this._firstUpdate = true;
  73161. },
  73162. enumerable: true,
  73163. configurable: true
  73164. });
  73165. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73166. /**
  73167. * Support test.
  73168. */
  73169. get: function () {
  73170. var engine = BABYLON.Engine.LastCreatedEngine;
  73171. if (!engine) {
  73172. return false;
  73173. }
  73174. return engine.getCaps().drawBuffersExtension;
  73175. },
  73176. enumerable: true,
  73177. configurable: true
  73178. });
  73179. // Public Methods
  73180. /**
  73181. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73182. */
  73183. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73184. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73185. for (var i = 0; i < this._scene.cameras.length; i++) {
  73186. var camera = this._scene.cameras[i];
  73187. this._originalColorPostProcess.dispose(camera);
  73188. this._ssaoPostProcess.dispose(camera);
  73189. this._blurHPostProcess.dispose(camera);
  73190. this._blurVPostProcess.dispose(camera);
  73191. this._ssaoCombinePostProcess.dispose(camera);
  73192. }
  73193. this._randomTexture.dispose();
  73194. if (disableGeometryBufferRenderer)
  73195. this._scene.disableGeometryBufferRenderer();
  73196. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73197. _super.prototype.dispose.call(this);
  73198. };
  73199. // Private Methods
  73200. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73201. var _this = this;
  73202. this._samplerOffsets = [];
  73203. var expensive = this.expensiveBlur;
  73204. for (var i = -8; i < 8; i++) {
  73205. this._samplerOffsets.push(i * 2 + 0.5);
  73206. }
  73207. 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");
  73208. this._blurHPostProcess.onApply = function (effect) {
  73209. if (!_this._scene.activeCamera) {
  73210. return;
  73211. }
  73212. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73213. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73214. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73215. effect.setFloat("radius", _this.radius);
  73216. effect.setTexture("depthSampler", _this._depthTexture);
  73217. if (_this._firstUpdate) {
  73218. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73219. }
  73220. };
  73221. 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");
  73222. this._blurVPostProcess.onApply = function (effect) {
  73223. if (!_this._scene.activeCamera) {
  73224. return;
  73225. }
  73226. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73227. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73228. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73229. effect.setFloat("radius", _this.radius);
  73230. effect.setTexture("depthSampler", _this._depthTexture);
  73231. if (_this._firstUpdate) {
  73232. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73233. _this._firstUpdate = false;
  73234. }
  73235. };
  73236. };
  73237. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73238. this._firstUpdate = true;
  73239. _super.prototype._rebuild.call(this);
  73240. };
  73241. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73242. var numSamples = this.samples;
  73243. var result = [];
  73244. var vector, scale;
  73245. var rand = function (min, max) {
  73246. return Math.random() * (max - min) + min;
  73247. };
  73248. var i = 0;
  73249. while (i < numSamples) {
  73250. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73251. vector.normalize();
  73252. scale = i / numSamples;
  73253. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73254. vector.scaleInPlace(scale);
  73255. result.push(vector.x, vector.y, vector.z);
  73256. i++;
  73257. }
  73258. return result;
  73259. };
  73260. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73261. var _this = this;
  73262. var numSamples = this.samples;
  73263. this._sampleSphere = this._generateHemisphere();
  73264. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73265. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73266. "base", "range", "projection", "near", "far", "texelSize",
  73267. "xViewport", "yViewport", "maxZ", "minZAspect"
  73268. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73269. this._ssaoPostProcess.onApply = function (effect) {
  73270. if (_this._firstUpdate) {
  73271. effect.setArray3("sampleSphere", _this._sampleSphere);
  73272. effect.setFloat("randTextureTiles", 4.0);
  73273. }
  73274. if (!_this._scene.activeCamera) {
  73275. return;
  73276. }
  73277. effect.setFloat("samplesFactor", 1 / _this.samples);
  73278. effect.setFloat("totalStrength", _this.totalStrength);
  73279. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73280. effect.setFloat("radius", _this.radius);
  73281. effect.setFloat("maxZ", _this.maxZ);
  73282. effect.setFloat("minZAspect", _this.minZAspect);
  73283. effect.setFloat("base", _this.base);
  73284. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73285. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73286. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73287. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73288. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73289. effect.setTexture("textureSampler", _this._depthTexture);
  73290. effect.setTexture("normalSampler", _this._normalTexture);
  73291. effect.setTexture("randomSampler", _this._randomTexture);
  73292. };
  73293. };
  73294. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73295. var _this = this;
  73296. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73297. this._ssaoCombinePostProcess.onApply = function (effect) {
  73298. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73299. };
  73300. };
  73301. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73302. var size = 512;
  73303. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73304. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73305. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73306. var context = this._randomTexture.getContext();
  73307. var rand = function (min, max) {
  73308. return Math.random() * (max - min) + min;
  73309. };
  73310. var randVector = BABYLON.Vector3.Zero();
  73311. for (var x = 0; x < size; x++) {
  73312. for (var y = 0; y < size; y++) {
  73313. randVector.x = rand(0.0, 1.0);
  73314. randVector.y = rand(0.0, 1.0);
  73315. randVector.z = 0.0;
  73316. randVector.normalize();
  73317. randVector.scaleInPlace(255);
  73318. randVector.x = Math.floor(randVector.x);
  73319. randVector.y = Math.floor(randVector.y);
  73320. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73321. context.fillRect(x, y, 1, 1);
  73322. }
  73323. }
  73324. this._randomTexture.update(false);
  73325. };
  73326. /**
  73327. * Serialize the rendering pipeline (Used when exporting)
  73328. * @returns the serialized object
  73329. */
  73330. SSAO2RenderingPipeline.prototype.serialize = function () {
  73331. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73332. serializationObject.customType = "SSAO2RenderingPipeline";
  73333. return serializationObject;
  73334. };
  73335. /**
  73336. * Parse the serialized pipeline
  73337. * @param source Source pipeline.
  73338. * @param scene The scene to load the pipeline to.
  73339. * @param rootUrl The URL of the serialized pipeline.
  73340. * @returns An instantiated pipeline from the serialized object.
  73341. */
  73342. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73343. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73344. };
  73345. __decorate([
  73346. BABYLON.serialize()
  73347. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73348. __decorate([
  73349. BABYLON.serialize()
  73350. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73351. __decorate([
  73352. BABYLON.serialize()
  73353. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73354. __decorate([
  73355. BABYLON.serialize("samples")
  73356. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73357. __decorate([
  73358. BABYLON.serialize()
  73359. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73360. __decorate([
  73361. BABYLON.serialize("expensiveBlur")
  73362. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73363. __decorate([
  73364. BABYLON.serialize()
  73365. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73366. __decorate([
  73367. BABYLON.serialize()
  73368. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73369. return SSAO2RenderingPipeline;
  73370. }(BABYLON.PostProcessRenderPipeline));
  73371. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73372. })(BABYLON || (BABYLON = {}));
  73373. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73374. // BABYLON.JS Chromatic Aberration GLSL Shader
  73375. // Author: Olivier Guyot
  73376. // Separates very slightly R, G and B colors on the edges of the screen
  73377. // Inspired by Francois Tarlier & Martins Upitis
  73378. var BABYLON;
  73379. (function (BABYLON) {
  73380. var LensRenderingPipeline = /** @class */ (function (_super) {
  73381. __extends(LensRenderingPipeline, _super);
  73382. /**
  73383. * @constructor
  73384. *
  73385. * Effect parameters are as follow:
  73386. * {
  73387. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73388. * edge_blur: number; // from 0 to x (1 for realism)
  73389. * distortion: number; // from 0 to x (1 for realism)
  73390. * grain_amount: number; // from 0 to 1
  73391. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73392. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73393. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73394. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73395. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73396. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73397. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73398. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73399. * }
  73400. * Note: if an effect parameter is unset, effect is disabled
  73401. *
  73402. * @param {string} name - The rendering pipeline name
  73403. * @param {object} parameters - An object containing all parameters (see above)
  73404. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73405. * @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)
  73406. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73407. */
  73408. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73409. if (ratio === void 0) { ratio = 1.0; }
  73410. var _this = _super.call(this, scene.getEngine(), name) || this;
  73411. // Lens effects can be of the following:
  73412. // - chromatic aberration (slight shift of RGB colors)
  73413. // - blur on the edge of the lens
  73414. // - lens distortion
  73415. // - depth-of-field blur & highlights enhancing
  73416. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73417. // - grain effect (noise or custom texture)
  73418. // Two additional texture samplers are needed:
  73419. // - depth map (for depth-of-field)
  73420. // - grain texture
  73421. /**
  73422. * The chromatic aberration PostProcess id in the pipeline
  73423. */
  73424. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73425. /**
  73426. * The highlights enhancing PostProcess id in the pipeline
  73427. */
  73428. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73429. /**
  73430. * The depth-of-field PostProcess id in the pipeline
  73431. */
  73432. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73433. _this._scene = scene;
  73434. // Fetch texture samplers
  73435. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73436. if (parameters.grain_texture) {
  73437. _this._grainTexture = parameters.grain_texture;
  73438. }
  73439. else {
  73440. _this._createGrainTexture();
  73441. }
  73442. // save parameters
  73443. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73444. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73445. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73446. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73447. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73448. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73449. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73450. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73451. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73452. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73453. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73454. // Create effects
  73455. _this._createChromaticAberrationPostProcess(ratio);
  73456. _this._createHighlightsPostProcess(ratio);
  73457. _this._createDepthOfFieldPostProcess(ratio / 4);
  73458. // Set up pipeline
  73459. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73460. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73461. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73462. if (_this._highlightsGain === -1) {
  73463. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73464. }
  73465. // Finish
  73466. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73467. if (cameras) {
  73468. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73469. }
  73470. return _this;
  73471. }
  73472. // public methods (self explanatory)
  73473. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73474. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73475. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73476. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73477. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73478. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73479. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73480. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73481. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73482. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73483. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73484. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73485. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73486. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73487. };
  73488. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73489. this._highlightsPostProcess.updateEffect();
  73490. };
  73491. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73492. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73493. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73494. this._highlightsGain = amount;
  73495. };
  73496. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73497. if (this._highlightsGain === -1) {
  73498. this._highlightsGain = 1.0;
  73499. }
  73500. this._highlightsThreshold = amount;
  73501. };
  73502. LensRenderingPipeline.prototype.disableHighlights = function () {
  73503. this._highlightsGain = -1;
  73504. };
  73505. /**
  73506. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73507. */
  73508. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73509. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73510. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73511. this._chromaticAberrationPostProcess = null;
  73512. this._highlightsPostProcess = null;
  73513. this._depthOfFieldPostProcess = null;
  73514. this._grainTexture.dispose();
  73515. if (disableDepthRender)
  73516. this._scene.disableDepthRenderer();
  73517. };
  73518. // colors shifting and distortion
  73519. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73520. var _this = this;
  73521. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73522. [], // samplers
  73523. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73524. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73525. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73526. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73527. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73528. effect.setFloat('radialIntensity', 1);
  73529. effect.setFloat2('direction', 17, 17);
  73530. effect.setFloat2('centerPosition', 0.5, 0.5);
  73531. };
  73532. };
  73533. // highlights enhancing
  73534. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73535. var _this = this;
  73536. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73537. [], // samplers
  73538. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73539. this._highlightsPostProcess.onApply = function (effect) {
  73540. effect.setFloat('gain', _this._highlightsGain);
  73541. effect.setFloat('threshold', _this._highlightsThreshold);
  73542. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73543. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73544. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73545. };
  73546. };
  73547. // colors shifting and distortion
  73548. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73549. var _this = this;
  73550. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73551. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73552. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73553. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73554. this._depthOfFieldPostProcess.onApply = function (effect) {
  73555. effect.setTexture("depthSampler", _this._depthTexture);
  73556. effect.setTexture("grainSampler", _this._grainTexture);
  73557. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73558. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73559. effect.setFloat('grain_amount', _this._grainAmount);
  73560. effect.setBool('blur_noise', _this._blurNoise);
  73561. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73562. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73563. effect.setFloat('distortion', _this._distortion);
  73564. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73565. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73566. effect.setFloat('aperture', _this._dofAperture);
  73567. effect.setFloat('darken', _this._dofDarken);
  73568. effect.setFloat('edge_blur', _this._edgeBlur);
  73569. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73570. if (_this._scene.activeCamera) {
  73571. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73572. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73573. }
  73574. };
  73575. };
  73576. // creates a black and white random noise texture, 512x512
  73577. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73578. var size = 512;
  73579. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73580. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73581. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73582. var context = this._grainTexture.getContext();
  73583. var rand = function (min, max) {
  73584. return Math.random() * (max - min) + min;
  73585. };
  73586. var value;
  73587. for (var x = 0; x < size; x++) {
  73588. for (var y = 0; y < size; y++) {
  73589. value = Math.floor(rand(0.42, 0.58) * 255);
  73590. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73591. context.fillRect(x, y, 1, 1);
  73592. }
  73593. }
  73594. this._grainTexture.update(false);
  73595. };
  73596. return LensRenderingPipeline;
  73597. }(BABYLON.PostProcessRenderPipeline));
  73598. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73599. })(BABYLON || (BABYLON = {}));
  73600. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73601. var BABYLON;
  73602. (function (BABYLON) {
  73603. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73604. __extends(StandardRenderingPipeline, _super);
  73605. /**
  73606. * @constructor
  73607. * @param {string} name - The rendering pipeline name
  73608. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73609. * @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)
  73610. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73611. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73612. */
  73613. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73614. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73615. var _this = _super.call(this, scene.getEngine(), name) || this;
  73616. _this.downSampleX4PostProcess = null;
  73617. _this.brightPassPostProcess = null;
  73618. _this.blurHPostProcesses = [];
  73619. _this.blurVPostProcesses = [];
  73620. _this.textureAdderPostProcess = null;
  73621. _this.volumetricLightPostProcess = null;
  73622. _this.volumetricLightSmoothXPostProcess = null;
  73623. _this.volumetricLightSmoothYPostProcess = null;
  73624. _this.volumetricLightMergePostProces = null;
  73625. _this.volumetricLightFinalPostProcess = null;
  73626. _this.luminancePostProcess = null;
  73627. _this.luminanceDownSamplePostProcesses = [];
  73628. _this.hdrPostProcess = null;
  73629. _this.textureAdderFinalPostProcess = null;
  73630. _this.lensFlareFinalPostProcess = null;
  73631. _this.hdrFinalPostProcess = null;
  73632. _this.lensFlarePostProcess = null;
  73633. _this.lensFlareComposePostProcess = null;
  73634. _this.motionBlurPostProcess = null;
  73635. _this.depthOfFieldPostProcess = null;
  73636. // Values
  73637. _this.brightThreshold = 1.0;
  73638. _this.blurWidth = 512.0;
  73639. _this.horizontalBlur = false;
  73640. _this.exposure = 1.0;
  73641. _this.lensTexture = null;
  73642. _this.volumetricLightCoefficient = 0.2;
  73643. _this.volumetricLightPower = 4.0;
  73644. _this.volumetricLightBlurScale = 64.0;
  73645. _this.sourceLight = null;
  73646. _this.hdrMinimumLuminance = 1.0;
  73647. _this.hdrDecreaseRate = 0.5;
  73648. _this.hdrIncreaseRate = 0.5;
  73649. _this.lensColorTexture = null;
  73650. _this.lensFlareStrength = 20.0;
  73651. _this.lensFlareGhostDispersal = 1.4;
  73652. _this.lensFlareHaloWidth = 0.7;
  73653. _this.lensFlareDistortionStrength = 16.0;
  73654. _this.lensStarTexture = null;
  73655. _this.lensFlareDirtTexture = null;
  73656. _this.depthOfFieldDistance = 10.0;
  73657. _this.depthOfFieldBlurWidth = 64.0;
  73658. _this.motionStrength = 1.0;
  73659. // IAnimatable
  73660. _this.animations = [];
  73661. _this._currentDepthOfFieldSource = null;
  73662. _this._hdrCurrentLuminance = 1.0;
  73663. // Getters and setters
  73664. _this._bloomEnabled = true;
  73665. _this._depthOfFieldEnabled = false;
  73666. _this._vlsEnabled = false;
  73667. _this._lensFlareEnabled = false;
  73668. _this._hdrEnabled = false;
  73669. _this._motionBlurEnabled = false;
  73670. _this._motionBlurSamples = 64.0;
  73671. _this._volumetricLightStepsCount = 50.0;
  73672. _this._cameras = cameras || [];
  73673. // Initialize
  73674. _this._scene = scene;
  73675. _this._basePostProcess = originalPostProcess;
  73676. _this._ratio = ratio;
  73677. // Misc
  73678. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73679. // Finish
  73680. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73681. _this._buildPipeline();
  73682. return _this;
  73683. }
  73684. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73685. get: function () {
  73686. return this._bloomEnabled;
  73687. },
  73688. set: function (enabled) {
  73689. if (this._bloomEnabled === enabled) {
  73690. return;
  73691. }
  73692. this._bloomEnabled = enabled;
  73693. this._buildPipeline();
  73694. },
  73695. enumerable: true,
  73696. configurable: true
  73697. });
  73698. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73699. get: function () {
  73700. return this._depthOfFieldEnabled;
  73701. },
  73702. set: function (enabled) {
  73703. if (this._depthOfFieldEnabled === enabled) {
  73704. return;
  73705. }
  73706. this._depthOfFieldEnabled = enabled;
  73707. this._buildPipeline();
  73708. },
  73709. enumerable: true,
  73710. configurable: true
  73711. });
  73712. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73713. get: function () {
  73714. return this._lensFlareEnabled;
  73715. },
  73716. set: function (enabled) {
  73717. if (this._lensFlareEnabled === enabled) {
  73718. return;
  73719. }
  73720. this._lensFlareEnabled = enabled;
  73721. this._buildPipeline();
  73722. },
  73723. enumerable: true,
  73724. configurable: true
  73725. });
  73726. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73727. get: function () {
  73728. return this._hdrEnabled;
  73729. },
  73730. set: function (enabled) {
  73731. if (this._hdrEnabled === enabled) {
  73732. return;
  73733. }
  73734. this._hdrEnabled = enabled;
  73735. this._buildPipeline();
  73736. },
  73737. enumerable: true,
  73738. configurable: true
  73739. });
  73740. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73741. get: function () {
  73742. return this._vlsEnabled;
  73743. },
  73744. set: function (enabled) {
  73745. if (this._vlsEnabled === enabled) {
  73746. return;
  73747. }
  73748. if (enabled) {
  73749. var geometry = this._scene.enableGeometryBufferRenderer();
  73750. if (!geometry) {
  73751. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73752. return;
  73753. }
  73754. }
  73755. this._vlsEnabled = enabled;
  73756. this._buildPipeline();
  73757. },
  73758. enumerable: true,
  73759. configurable: true
  73760. });
  73761. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73762. get: function () {
  73763. return this._motionBlurEnabled;
  73764. },
  73765. set: function (enabled) {
  73766. if (this._motionBlurEnabled === enabled) {
  73767. return;
  73768. }
  73769. this._motionBlurEnabled = enabled;
  73770. this._buildPipeline();
  73771. },
  73772. enumerable: true,
  73773. configurable: true
  73774. });
  73775. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73776. get: function () {
  73777. return this._volumetricLightStepsCount;
  73778. },
  73779. set: function (count) {
  73780. if (this.volumetricLightPostProcess) {
  73781. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73782. }
  73783. this._volumetricLightStepsCount = count;
  73784. },
  73785. enumerable: true,
  73786. configurable: true
  73787. });
  73788. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73789. get: function () {
  73790. return this._motionBlurSamples;
  73791. },
  73792. set: function (samples) {
  73793. if (this.motionBlurPostProcess) {
  73794. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73795. }
  73796. this._motionBlurSamples = samples;
  73797. },
  73798. enumerable: true,
  73799. configurable: true
  73800. });
  73801. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73802. var _this = this;
  73803. var ratio = this._ratio;
  73804. var scene = this._scene;
  73805. this._disposePostProcesses();
  73806. this._reset();
  73807. // Create pass post-process
  73808. if (!this._basePostProcess) {
  73809. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73810. this.originalPostProcess.onApply = function (effect) {
  73811. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73812. };
  73813. }
  73814. else {
  73815. this.originalPostProcess = this._basePostProcess;
  73816. }
  73817. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73818. this._currentDepthOfFieldSource = this.originalPostProcess;
  73819. if (this._bloomEnabled) {
  73820. // Create down sample X4 post-process
  73821. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73822. // Create bright pass post-process
  73823. this._createBrightPassPostProcess(scene, ratio / 2);
  73824. // Create gaussian blur post-processes (down sampling blurs)
  73825. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73826. // Create texture adder post-process
  73827. this._createTextureAdderPostProcess(scene, ratio);
  73828. // Create depth-of-field source post-process
  73829. 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);
  73830. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73831. }
  73832. if (this._vlsEnabled) {
  73833. // Create volumetric light
  73834. this._createVolumetricLightPostProcess(scene, ratio);
  73835. // Create volumetric light final post-process
  73836. 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);
  73837. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73838. }
  73839. if (this._lensFlareEnabled) {
  73840. // Create lens flare post-process
  73841. this._createLensFlarePostProcess(scene, ratio);
  73842. // Create depth-of-field source post-process post lens-flare and disable it now
  73843. 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);
  73844. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73845. }
  73846. if (this._hdrEnabled) {
  73847. // Create luminance
  73848. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73849. // Create HDR
  73850. this._createHdrPostProcess(scene, ratio);
  73851. // Create depth-of-field source post-process post hdr and disable it now
  73852. 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);
  73853. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73854. }
  73855. if (this._depthOfFieldEnabled) {
  73856. // Create gaussian blur used by depth-of-field
  73857. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73858. // Create depth-of-field post-process
  73859. this._createDepthOfFieldPostProcess(scene, ratio);
  73860. }
  73861. if (this._motionBlurEnabled) {
  73862. // Create motion blur post-process
  73863. this._createMotionBlurPostProcess(scene, ratio);
  73864. }
  73865. if (this._cameras !== null) {
  73866. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73867. }
  73868. };
  73869. // Down Sample X4 Post-Processs
  73870. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73871. var _this = this;
  73872. var downSampleX4Offsets = new Array(32);
  73873. 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);
  73874. this.downSampleX4PostProcess.onApply = function (effect) {
  73875. var id = 0;
  73876. var width = _this.downSampleX4PostProcess.width;
  73877. var height = _this.downSampleX4PostProcess.height;
  73878. for (var i = -2; i < 2; i++) {
  73879. for (var j = -2; j < 2; j++) {
  73880. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73881. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73882. id += 2;
  73883. }
  73884. }
  73885. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73886. };
  73887. // Add to pipeline
  73888. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73889. };
  73890. // Brightpass Post-Process
  73891. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73892. var _this = this;
  73893. var brightOffsets = new Array(8);
  73894. 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);
  73895. this.brightPassPostProcess.onApply = function (effect) {
  73896. var sU = (1.0 / _this.brightPassPostProcess.width);
  73897. var sV = (1.0 / _this.brightPassPostProcess.height);
  73898. brightOffsets[0] = -0.5 * sU;
  73899. brightOffsets[1] = 0.5 * sV;
  73900. brightOffsets[2] = 0.5 * sU;
  73901. brightOffsets[3] = 0.5 * sV;
  73902. brightOffsets[4] = -0.5 * sU;
  73903. brightOffsets[5] = -0.5 * sV;
  73904. brightOffsets[6] = 0.5 * sU;
  73905. brightOffsets[7] = -0.5 * sV;
  73906. effect.setArray2("dsOffsets", brightOffsets);
  73907. effect.setFloat("brightThreshold", _this.brightThreshold);
  73908. };
  73909. // Add to pipeline
  73910. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73911. };
  73912. // Create blur H&V post-processes
  73913. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73914. var _this = this;
  73915. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73916. var engine = scene.getEngine();
  73917. 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);
  73918. 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);
  73919. blurX.onActivateObservable.add(function () {
  73920. var dw = blurX.width / engine.getRenderWidth();
  73921. blurX.kernel = _this[blurWidthKey] * dw;
  73922. });
  73923. blurY.onActivateObservable.add(function () {
  73924. var dw = blurY.height / engine.getRenderHeight();
  73925. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73926. });
  73927. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73928. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73929. this.blurHPostProcesses.push(blurX);
  73930. this.blurVPostProcesses.push(blurY);
  73931. };
  73932. // Create texture adder post-process
  73933. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73934. var _this = this;
  73935. 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);
  73936. this.textureAdderPostProcess.onApply = function (effect) {
  73937. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73938. effect.setTexture("lensSampler", _this.lensTexture);
  73939. effect.setFloat("exposure", _this.exposure);
  73940. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73941. };
  73942. // Add to pipeline
  73943. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73944. };
  73945. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73946. var _this = this;
  73947. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73948. geometryRenderer.enablePosition = true;
  73949. var geometry = geometryRenderer.getGBuffer();
  73950. // Base post-process
  73951. 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));
  73952. var depthValues = BABYLON.Vector2.Zero();
  73953. this.volumetricLightPostProcess.onApply = function (effect) {
  73954. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73955. var generator = _this.sourceLight.getShadowGenerator();
  73956. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73957. effect.setTexture("positionSampler", geometry.textures[2]);
  73958. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73959. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73960. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73961. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73962. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73963. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73964. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73965. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73966. effect.setVector2("depthValues", depthValues);
  73967. }
  73968. };
  73969. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73970. // Smooth
  73971. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73972. // Merge
  73973. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73974. this.volumetricLightMergePostProces.onApply = function (effect) {
  73975. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  73976. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73977. };
  73978. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73979. };
  73980. // Create luminance
  73981. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73982. var _this = this;
  73983. // Create luminance
  73984. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73985. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73986. var offsets = [];
  73987. this.luminancePostProcess.onApply = function (effect) {
  73988. var sU = (1.0 / _this.luminancePostProcess.width);
  73989. var sV = (1.0 / _this.luminancePostProcess.height);
  73990. offsets[0] = -0.5 * sU;
  73991. offsets[1] = 0.5 * sV;
  73992. offsets[2] = 0.5 * sU;
  73993. offsets[3] = 0.5 * sV;
  73994. offsets[4] = -0.5 * sU;
  73995. offsets[5] = -0.5 * sV;
  73996. offsets[6] = 0.5 * sU;
  73997. offsets[7] = -0.5 * sV;
  73998. effect.setArray2("lumOffsets", offsets);
  73999. };
  74000. // Add to pipeline
  74001. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74002. // Create down sample luminance
  74003. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74004. var size = Math.pow(3, i);
  74005. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74006. if (i === 0) {
  74007. defines += "#define FINAL_DOWN_SAMPLER";
  74008. }
  74009. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74010. this.luminanceDownSamplePostProcesses.push(postProcess);
  74011. }
  74012. // Create callbacks and add effects
  74013. var lastLuminance = this.luminancePostProcess;
  74014. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74015. var downSampleOffsets = new Array(18);
  74016. pp.onApply = function (effect) {
  74017. if (!lastLuminance) {
  74018. return;
  74019. }
  74020. var id = 0;
  74021. for (var x = -1; x < 2; x++) {
  74022. for (var y = -1; y < 2; y++) {
  74023. downSampleOffsets[id] = x / lastLuminance.width;
  74024. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74025. id += 2;
  74026. }
  74027. }
  74028. effect.setArray2("dsOffsets", downSampleOffsets);
  74029. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74030. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74031. lastLuminance = _this.luminancePostProcess;
  74032. }
  74033. else {
  74034. lastLuminance = pp;
  74035. }
  74036. };
  74037. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74038. pp.onAfterRender = function (effect) {
  74039. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74040. 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);
  74041. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74042. };
  74043. }
  74044. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74045. });
  74046. };
  74047. // Create HDR post-process
  74048. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74049. var _this = this;
  74050. 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);
  74051. var outputLiminance = 1;
  74052. var time = 0;
  74053. var lastTime = 0;
  74054. this.hdrPostProcess.onApply = function (effect) {
  74055. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74056. time += scene.getEngine().getDeltaTime();
  74057. if (outputLiminance < 0) {
  74058. outputLiminance = _this._hdrCurrentLuminance;
  74059. }
  74060. else {
  74061. var dt = (lastTime - time) / 1000.0;
  74062. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74063. outputLiminance += _this.hdrDecreaseRate * dt;
  74064. }
  74065. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74066. outputLiminance -= _this.hdrIncreaseRate * dt;
  74067. }
  74068. else {
  74069. outputLiminance = _this._hdrCurrentLuminance;
  74070. }
  74071. }
  74072. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74073. effect.setFloat("averageLuminance", outputLiminance);
  74074. lastTime = time;
  74075. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74076. };
  74077. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74078. };
  74079. // Create lens flare post-process
  74080. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74081. var _this = this;
  74082. 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);
  74083. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74084. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74085. 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);
  74086. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74087. var resolution = new BABYLON.Vector2(0, 0);
  74088. // Lens flare
  74089. this.lensFlarePostProcess.onApply = function (effect) {
  74090. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74091. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74092. effect.setFloat("strength", _this.lensFlareStrength);
  74093. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74094. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74095. // Shift
  74096. resolution.x = _this.lensFlarePostProcess.width;
  74097. resolution.y = _this.lensFlarePostProcess.height;
  74098. effect.setVector2("resolution", resolution);
  74099. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74100. };
  74101. // Compose
  74102. 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);
  74103. 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);
  74104. this.lensFlareComposePostProcess.onApply = function (effect) {
  74105. if (!_this._scene.activeCamera) {
  74106. return;
  74107. }
  74108. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74109. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74110. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74111. // Lens start rotation matrix
  74112. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74113. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74114. 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));
  74115. camRot *= 4.0;
  74116. 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);
  74117. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74118. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74119. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74120. };
  74121. };
  74122. // Create depth-of-field post-process
  74123. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74124. var _this = this;
  74125. 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);
  74126. this.depthOfFieldPostProcess.onApply = function (effect) {
  74127. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74128. effect.setTexture("depthSampler", _this._getDepthTexture());
  74129. effect.setFloat("distance", _this.depthOfFieldDistance);
  74130. };
  74131. // Add to pipeline
  74132. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74133. };
  74134. // Create motion blur post-process
  74135. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74136. var _this = this;
  74137. 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);
  74138. var motionScale = 0;
  74139. var prevViewProjection = BABYLON.Matrix.Identity();
  74140. var invViewProjection = BABYLON.Matrix.Identity();
  74141. var viewProjection = BABYLON.Matrix.Identity();
  74142. var screenSize = BABYLON.Vector2.Zero();
  74143. this.motionBlurPostProcess.onApply = function (effect) {
  74144. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74145. viewProjection.invertToRef(invViewProjection);
  74146. effect.setMatrix("inverseViewProjection", invViewProjection);
  74147. effect.setMatrix("prevViewProjection", prevViewProjection);
  74148. prevViewProjection = viewProjection;
  74149. screenSize.x = _this.motionBlurPostProcess.width;
  74150. screenSize.y = _this.motionBlurPostProcess.height;
  74151. effect.setVector2("screenSize", screenSize);
  74152. motionScale = scene.getEngine().getFps() / 60.0;
  74153. effect.setFloat("motionScale", motionScale);
  74154. effect.setFloat("motionStrength", _this.motionStrength);
  74155. effect.setTexture("depthSampler", _this._getDepthTexture());
  74156. };
  74157. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74158. };
  74159. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74160. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74161. var renderer = this._scene.enableGeometryBufferRenderer();
  74162. return renderer.getGBuffer().textures[0];
  74163. }
  74164. return this._scene.enableDepthRenderer().getDepthMap();
  74165. };
  74166. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74167. for (var i = 0; i < this._cameras.length; i++) {
  74168. var camera = this._cameras[i];
  74169. if (this.originalPostProcess) {
  74170. this.originalPostProcess.dispose(camera);
  74171. }
  74172. if (this.downSampleX4PostProcess) {
  74173. this.downSampleX4PostProcess.dispose(camera);
  74174. }
  74175. if (this.brightPassPostProcess) {
  74176. this.brightPassPostProcess.dispose(camera);
  74177. }
  74178. if (this.textureAdderPostProcess) {
  74179. this.textureAdderPostProcess.dispose(camera);
  74180. }
  74181. if (this.textureAdderFinalPostProcess) {
  74182. this.textureAdderFinalPostProcess.dispose(camera);
  74183. }
  74184. if (this.volumetricLightPostProcess) {
  74185. this.volumetricLightPostProcess.dispose(camera);
  74186. }
  74187. if (this.volumetricLightSmoothXPostProcess) {
  74188. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74189. }
  74190. if (this.volumetricLightSmoothYPostProcess) {
  74191. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74192. }
  74193. if (this.volumetricLightMergePostProces) {
  74194. this.volumetricLightMergePostProces.dispose(camera);
  74195. }
  74196. if (this.volumetricLightFinalPostProcess) {
  74197. this.volumetricLightFinalPostProcess.dispose(camera);
  74198. }
  74199. if (this.lensFlarePostProcess) {
  74200. this.lensFlarePostProcess.dispose(camera);
  74201. }
  74202. if (this.lensFlareComposePostProcess) {
  74203. this.lensFlareComposePostProcess.dispose(camera);
  74204. }
  74205. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74206. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74207. }
  74208. if (this.luminancePostProcess) {
  74209. this.luminancePostProcess.dispose(camera);
  74210. }
  74211. if (this.hdrPostProcess) {
  74212. this.hdrPostProcess.dispose(camera);
  74213. }
  74214. if (this.hdrFinalPostProcess) {
  74215. this.hdrFinalPostProcess.dispose(camera);
  74216. }
  74217. if (this.depthOfFieldPostProcess) {
  74218. this.depthOfFieldPostProcess.dispose(camera);
  74219. }
  74220. if (this.motionBlurPostProcess) {
  74221. this.motionBlurPostProcess.dispose(camera);
  74222. }
  74223. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74224. this.blurHPostProcesses[j].dispose(camera);
  74225. }
  74226. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74227. this.blurVPostProcesses[j].dispose(camera);
  74228. }
  74229. }
  74230. this.originalPostProcess = null;
  74231. this.downSampleX4PostProcess = null;
  74232. this.brightPassPostProcess = null;
  74233. this.textureAdderPostProcess = null;
  74234. this.textureAdderFinalPostProcess = null;
  74235. this.volumetricLightPostProcess = null;
  74236. this.volumetricLightSmoothXPostProcess = null;
  74237. this.volumetricLightSmoothYPostProcess = null;
  74238. this.volumetricLightMergePostProces = null;
  74239. this.volumetricLightFinalPostProcess = null;
  74240. this.lensFlarePostProcess = null;
  74241. this.lensFlareComposePostProcess = null;
  74242. this.luminancePostProcess = null;
  74243. this.hdrPostProcess = null;
  74244. this.hdrFinalPostProcess = null;
  74245. this.depthOfFieldPostProcess = null;
  74246. this.motionBlurPostProcess = null;
  74247. this.luminanceDownSamplePostProcesses = [];
  74248. this.blurHPostProcesses = [];
  74249. this.blurVPostProcesses = [];
  74250. };
  74251. /**
  74252. * Dispose of the pipeline and stop all post processes
  74253. */
  74254. StandardRenderingPipeline.prototype.dispose = function () {
  74255. this._disposePostProcesses();
  74256. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74257. _super.prototype.dispose.call(this);
  74258. };
  74259. /**
  74260. * Serialize the rendering pipeline (Used when exporting)
  74261. * @returns the serialized object
  74262. */
  74263. StandardRenderingPipeline.prototype.serialize = function () {
  74264. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74265. if (this.sourceLight) {
  74266. serializationObject.sourceLightId = this.sourceLight.id;
  74267. }
  74268. serializationObject.customType = "StandardRenderingPipeline";
  74269. return serializationObject;
  74270. };
  74271. /**
  74272. * Parse the serialized pipeline
  74273. * @param source Source pipeline.
  74274. * @param scene The scene to load the pipeline to.
  74275. * @param rootUrl The URL of the serialized pipeline.
  74276. * @returns An instantiated pipeline from the serialized object.
  74277. */
  74278. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74279. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74280. if (source.sourceLightId) {
  74281. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74282. }
  74283. return p;
  74284. };
  74285. // Luminance steps
  74286. StandardRenderingPipeline.LuminanceSteps = 6;
  74287. __decorate([
  74288. BABYLON.serialize()
  74289. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74290. __decorate([
  74291. BABYLON.serialize()
  74292. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74293. __decorate([
  74294. BABYLON.serialize()
  74295. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74296. __decorate([
  74297. BABYLON.serialize()
  74298. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74299. __decorate([
  74300. BABYLON.serializeAsTexture("lensTexture")
  74301. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74302. __decorate([
  74303. BABYLON.serialize()
  74304. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74305. __decorate([
  74306. BABYLON.serialize()
  74307. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74308. __decorate([
  74309. BABYLON.serialize()
  74310. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74311. __decorate([
  74312. BABYLON.serialize()
  74313. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74314. __decorate([
  74315. BABYLON.serialize()
  74316. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74317. __decorate([
  74318. BABYLON.serialize()
  74319. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74320. __decorate([
  74321. BABYLON.serializeAsTexture("lensColorTexture")
  74322. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74323. __decorate([
  74324. BABYLON.serialize()
  74325. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74326. __decorate([
  74327. BABYLON.serialize()
  74328. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74329. __decorate([
  74330. BABYLON.serialize()
  74331. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74332. __decorate([
  74333. BABYLON.serialize()
  74334. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74335. __decorate([
  74336. BABYLON.serializeAsTexture("lensStarTexture")
  74337. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74338. __decorate([
  74339. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74340. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74341. __decorate([
  74342. BABYLON.serialize()
  74343. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74344. __decorate([
  74345. BABYLON.serialize()
  74346. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74347. __decorate([
  74348. BABYLON.serialize()
  74349. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74350. __decorate([
  74351. BABYLON.serialize()
  74352. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74353. __decorate([
  74354. BABYLON.serialize()
  74355. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74356. __decorate([
  74357. BABYLON.serialize()
  74358. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74359. __decorate([
  74360. BABYLON.serialize()
  74361. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74362. __decorate([
  74363. BABYLON.serialize()
  74364. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74365. __decorate([
  74366. BABYLON.serialize()
  74367. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74368. __decorate([
  74369. BABYLON.serialize()
  74370. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74371. __decorate([
  74372. BABYLON.serialize()
  74373. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74374. __decorate([
  74375. BABYLON.serialize()
  74376. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74377. return StandardRenderingPipeline;
  74378. }(BABYLON.PostProcessRenderPipeline));
  74379. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74380. })(BABYLON || (BABYLON = {}));
  74381. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74382. var BABYLON;
  74383. (function (BABYLON) {
  74384. var FxaaPostProcess = /** @class */ (function (_super) {
  74385. __extends(FxaaPostProcess, _super);
  74386. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74387. if (camera === void 0) { camera = null; }
  74388. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74389. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74390. var defines = _this._getDefines();
  74391. _this.updateEffect(defines);
  74392. _this.onApplyObservable.add(function (effect) {
  74393. var texelSize = _this.texelSize;
  74394. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74395. });
  74396. return _this;
  74397. }
  74398. FxaaPostProcess.prototype._getDefines = function () {
  74399. var engine = this.getEngine();
  74400. if (!engine) {
  74401. return null;
  74402. }
  74403. var glInfo = engine.getGlInfo();
  74404. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74405. return "#define MALI 1\n";
  74406. }
  74407. return null;
  74408. };
  74409. return FxaaPostProcess;
  74410. }(BABYLON.PostProcess));
  74411. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74412. })(BABYLON || (BABYLON = {}));
  74413. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74414. var BABYLON;
  74415. (function (BABYLON) {
  74416. /**
  74417. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74418. */
  74419. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74420. __extends(ChromaticAberrationPostProcess, _super);
  74421. /**
  74422. * Creates a new instance ChromaticAberrationPostProcess
  74423. * @param name The name of the effect.
  74424. * @param screenWidth The width of the screen to apply the effect on.
  74425. * @param screenHeight The height of the screen to apply the effect on.
  74426. * @param options The required width/height ratio to downsize to before computing the render pass.
  74427. * @param camera The camera to apply the render pass to.
  74428. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74429. * @param engine The engine which the post process will be applied. (default: current engine)
  74430. * @param reusable If the post process can be reused on the same frame. (default: false)
  74431. * @param textureType Type of textures used when performing the post process. (default: 0)
  74432. * @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)
  74433. */
  74434. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74435. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74436. if (blockCompilation === void 0) { blockCompilation = false; }
  74437. 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;
  74438. /**
  74439. * The amount of seperation of rgb channels (default: 30)
  74440. */
  74441. _this.aberrationAmount = 30;
  74442. /**
  74443. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74444. */
  74445. _this.radialIntensity = 0;
  74446. /**
  74447. * 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))
  74448. */
  74449. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74450. /**
  74451. * 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))
  74452. */
  74453. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74454. _this.onApplyObservable.add(function (effect) {
  74455. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74456. effect.setFloat('screen_width', screenWidth);
  74457. effect.setFloat('screen_height', screenHeight);
  74458. effect.setFloat('radialIntensity', _this.radialIntensity);
  74459. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74460. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74461. });
  74462. return _this;
  74463. }
  74464. return ChromaticAberrationPostProcess;
  74465. }(BABYLON.PostProcess));
  74466. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74467. })(BABYLON || (BABYLON = {}));
  74468. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74469. var BABYLON;
  74470. (function (BABYLON) {
  74471. /**
  74472. * The GrainPostProcess adds noise to the image at mid luminance levels
  74473. */
  74474. var GrainPostProcess = /** @class */ (function (_super) {
  74475. __extends(GrainPostProcess, _super);
  74476. /**
  74477. * Creates a new instance of @see GrainPostProcess
  74478. * @param name The name of the effect.
  74479. * @param options The required width/height ratio to downsize to before computing the render pass.
  74480. * @param camera The camera to apply the render pass to.
  74481. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74482. * @param engine The engine which the post process will be applied. (default: current engine)
  74483. * @param reusable If the post process can be reused on the same frame. (default: false)
  74484. * @param textureType Type of textures used when performing the post process. (default: 0)
  74485. * @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)
  74486. */
  74487. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74488. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74489. if (blockCompilation === void 0) { blockCompilation = false; }
  74490. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74491. /**
  74492. * The intensity of the grain added (default: 30)
  74493. */
  74494. _this.intensity = 30;
  74495. /**
  74496. * If the grain should be randomized on every frame
  74497. */
  74498. _this.animated = false;
  74499. _this.onApplyObservable.add(function (effect) {
  74500. effect.setFloat('intensity', _this.intensity);
  74501. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74502. });
  74503. return _this;
  74504. }
  74505. return GrainPostProcess;
  74506. }(BABYLON.PostProcess));
  74507. BABYLON.GrainPostProcess = GrainPostProcess;
  74508. })(BABYLON || (BABYLON = {}));
  74509. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74510. var BABYLON;
  74511. (function (BABYLON) {
  74512. /**
  74513. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74514. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74515. */
  74516. var SharpenPostProcess = /** @class */ (function (_super) {
  74517. __extends(SharpenPostProcess, _super);
  74518. /**
  74519. * Creates a new instance ConvolutionPostProcess
  74520. * @param name The name of the effect.
  74521. * @param options The required width/height ratio to downsize to before computing the render pass.
  74522. * @param camera The camera to apply the render pass to.
  74523. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74524. * @param engine The engine which the post process will be applied. (default: current engine)
  74525. * @param reusable If the post process can be reused on the same frame. (default: false)
  74526. * @param textureType Type of textures used when performing the post process. (default: 0)
  74527. * @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)
  74528. */
  74529. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74530. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74531. if (blockCompilation === void 0) { blockCompilation = false; }
  74532. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74533. /**
  74534. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74535. */
  74536. _this.colorAmount = 1.0;
  74537. /**
  74538. * How much sharpness should be applied (default: 0.3)
  74539. */
  74540. _this.edgeAmount = 0.3;
  74541. _this.onApply = function (effect) {
  74542. effect.setFloat2("screenSize", _this.width, _this.height);
  74543. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74544. };
  74545. return _this;
  74546. }
  74547. return SharpenPostProcess;
  74548. }(BABYLON.PostProcess));
  74549. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74550. })(BABYLON || (BABYLON = {}));
  74551. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74552. var BABYLON;
  74553. (function (BABYLON) {
  74554. /**
  74555. * The Blur Post Process which blurs an image based on a kernel and direction.
  74556. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74557. */
  74558. var BlurPostProcess = /** @class */ (function (_super) {
  74559. __extends(BlurPostProcess, _super);
  74560. /**
  74561. * Creates a new instance BlurPostProcess
  74562. * @param name The name of the effect.
  74563. * @param direction The direction in which to blur the image.
  74564. * @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.
  74565. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74566. * @param camera The camera to apply the render pass to.
  74567. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74568. * @param engine The engine which the post process will be applied. (default: current engine)
  74569. * @param reusable If the post process can be reused on the same frame. (default: false)
  74570. * @param textureType Type of textures used when performing the post process. (default: 0)
  74571. * @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)
  74572. */
  74573. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74574. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74575. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74576. if (defines === void 0) { defines = ""; }
  74577. if (blockCompilation === void 0) { blockCompilation = false; }
  74578. 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;
  74579. _this.direction = direction;
  74580. _this.blockCompilation = blockCompilation;
  74581. _this._packedFloat = false;
  74582. _this._staticDefines = "";
  74583. _this._staticDefines = defines;
  74584. _this.onApplyObservable.add(function (effect) {
  74585. if (_this._outputTexture) {
  74586. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74587. }
  74588. else {
  74589. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74590. }
  74591. });
  74592. _this.kernel = kernel;
  74593. return _this;
  74594. }
  74595. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74596. /**
  74597. * Gets the length in pixels of the blur sample region
  74598. */
  74599. get: function () {
  74600. return this._idealKernel;
  74601. },
  74602. /**
  74603. * Sets the length in pixels of the blur sample region
  74604. */
  74605. set: function (v) {
  74606. if (this._idealKernel === v) {
  74607. return;
  74608. }
  74609. v = Math.max(v, 1);
  74610. this._idealKernel = v;
  74611. this._kernel = this._nearestBestKernel(v);
  74612. if (!this.blockCompilation) {
  74613. this._updateParameters();
  74614. }
  74615. },
  74616. enumerable: true,
  74617. configurable: true
  74618. });
  74619. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74620. /**
  74621. * Gets wether or not the blur is unpacking/repacking floats
  74622. */
  74623. get: function () {
  74624. return this._packedFloat;
  74625. },
  74626. /**
  74627. * Sets wether or not the blur needs to unpack/repack floats
  74628. */
  74629. set: function (v) {
  74630. if (this._packedFloat === v) {
  74631. return;
  74632. }
  74633. this._packedFloat = v;
  74634. if (!this.blockCompilation) {
  74635. this._updateParameters();
  74636. }
  74637. },
  74638. enumerable: true,
  74639. configurable: true
  74640. });
  74641. /**
  74642. * Updates the effect with the current post process compile time values and recompiles the shader.
  74643. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74644. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74645. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74646. * @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
  74647. * @param onCompiled Called when the shader has been compiled.
  74648. * @param onError Called if there is an error when compiling a shader.
  74649. */
  74650. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74651. if (defines === void 0) { defines = null; }
  74652. if (uniforms === void 0) { uniforms = null; }
  74653. if (samplers === void 0) { samplers = null; }
  74654. this._updateParameters(onCompiled, onError);
  74655. };
  74656. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74657. // Generate sampling offsets and weights
  74658. var N = this._kernel;
  74659. var centerIndex = (N - 1) / 2;
  74660. // Generate Gaussian sampling weights over kernel
  74661. var offsets = [];
  74662. var weights = [];
  74663. var totalWeight = 0;
  74664. for (var i = 0; i < N; i++) {
  74665. var u = i / (N - 1);
  74666. var w = this._gaussianWeight(u * 2.0 - 1);
  74667. offsets[i] = (i - centerIndex);
  74668. weights[i] = w;
  74669. totalWeight += w;
  74670. }
  74671. // Normalize weights
  74672. for (var i = 0; i < weights.length; i++) {
  74673. weights[i] /= totalWeight;
  74674. }
  74675. // Optimize: combine samples to take advantage of hardware linear sampling
  74676. // Walk from left to center, combining pairs (symmetrically)
  74677. var linearSamplingWeights = [];
  74678. var linearSamplingOffsets = [];
  74679. var linearSamplingMap = [];
  74680. for (var i = 0; i <= centerIndex; i += 2) {
  74681. var j = Math.min(i + 1, Math.floor(centerIndex));
  74682. var singleCenterSample = i === j;
  74683. if (singleCenterSample) {
  74684. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74685. }
  74686. else {
  74687. var sharedCell = j === centerIndex;
  74688. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74689. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74690. if (offsetLinear === 0) {
  74691. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74692. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74693. }
  74694. else {
  74695. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74696. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74697. }
  74698. }
  74699. }
  74700. for (var i = 0; i < linearSamplingMap.length; i++) {
  74701. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74702. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74703. }
  74704. // Replace with optimized
  74705. offsets = linearSamplingOffsets;
  74706. weights = linearSamplingWeights;
  74707. // Generate shaders
  74708. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74709. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74710. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74711. var defines = "";
  74712. defines += this._staticDefines;
  74713. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74714. if (this._staticDefines.indexOf("DOF") != -1) {
  74715. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74716. varyingCount--;
  74717. }
  74718. for (var i = 0; i < varyingCount; i++) {
  74719. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74720. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74721. }
  74722. var depCount = 0;
  74723. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74724. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74725. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74726. depCount++;
  74727. }
  74728. if (this.packedFloat) {
  74729. defines += "#define PACKEDFLOAT 1";
  74730. }
  74731. this.blockCompilation = false;
  74732. _super.prototype.updateEffect.call(this, defines, null, null, {
  74733. varyingCount: varyingCount,
  74734. depCount: depCount
  74735. }, onCompiled, onError);
  74736. };
  74737. /**
  74738. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74739. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74740. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74741. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74742. * The gaps between physical kernels are compensated for in the weighting of the samples
  74743. * @param idealKernel Ideal blur kernel.
  74744. * @return Nearest best kernel.
  74745. */
  74746. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74747. var v = Math.round(idealKernel);
  74748. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74749. var k = _a[_i];
  74750. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74751. return Math.max(k, 3);
  74752. }
  74753. }
  74754. return Math.max(v, 3);
  74755. };
  74756. /**
  74757. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74758. * @param x The point on the Gaussian distribution to sample.
  74759. * @return the value of the Gaussian function at x.
  74760. */
  74761. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74762. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74763. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74764. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74765. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74766. // truncated at around 1.3% of peak strength.
  74767. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74768. var sigma = (1 / 3);
  74769. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74770. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74771. var weight = (1.0 / denominator) * Math.exp(exponent);
  74772. return weight;
  74773. };
  74774. /**
  74775. * Generates a string that can be used as a floating point number in GLSL.
  74776. * @param x Value to print.
  74777. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74778. * @return GLSL float string.
  74779. */
  74780. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74781. if (decimalFigures === void 0) { decimalFigures = 8; }
  74782. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74783. };
  74784. return BlurPostProcess;
  74785. }(BABYLON.PostProcess));
  74786. BABYLON.BlurPostProcess = BlurPostProcess;
  74787. })(BABYLON || (BABYLON = {}));
  74788. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74789. var BABYLON;
  74790. (function (BABYLON) {
  74791. /**
  74792. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74793. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74794. * based on samples that have a large difference in distance than the center pixel.
  74795. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74796. */
  74797. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74798. __extends(DepthOfFieldBlurPostProcess, _super);
  74799. /**
  74800. * Creates a new instance CircleOfConfusionPostProcess
  74801. * @param name The name of the effect.
  74802. * @param scene The scene the effect belongs to.
  74803. * @param direction The direction the blur should be applied.
  74804. * @param kernel The size of the kernel used to blur.
  74805. * @param options The required width/height ratio to downsize to before computing the render pass.
  74806. * @param camera The camera to apply the render pass to.
  74807. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74808. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74809. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74810. * @param engine The engine which the post process will be applied. (default: current engine)
  74811. * @param reusable If the post process can be reused on the same frame. (default: false)
  74812. * @param textureType Type of textures used when performing the post process. (default: 0)
  74813. * @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)
  74814. */
  74815. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74816. if (imageToBlur === void 0) { imageToBlur = null; }
  74817. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74818. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74819. if (blockCompilation === void 0) { blockCompilation = false; }
  74820. 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;
  74821. _this.direction = direction;
  74822. _this.onApplyObservable.add(function (effect) {
  74823. if (imageToBlur != null) {
  74824. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74825. }
  74826. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74827. if (scene.activeCamera) {
  74828. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74829. }
  74830. });
  74831. return _this;
  74832. }
  74833. return DepthOfFieldBlurPostProcess;
  74834. }(BABYLON.BlurPostProcess));
  74835. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74836. })(BABYLON || (BABYLON = {}));
  74837. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74838. var BABYLON;
  74839. (function (BABYLON) {
  74840. /**
  74841. * Options to be set when merging outputs from the default pipeline.
  74842. */
  74843. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74844. function DepthOfFieldMergePostProcessOptions() {
  74845. }
  74846. return DepthOfFieldMergePostProcessOptions;
  74847. }());
  74848. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74849. /**
  74850. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74851. */
  74852. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74853. __extends(DepthOfFieldMergePostProcess, _super);
  74854. /**
  74855. * Creates a new instance of DepthOfFieldMergePostProcess
  74856. * @param name The name of the effect.
  74857. * @param originalFromInput Post process which's input will be used for the merge.
  74858. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74859. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74860. * @param options The required width/height ratio to downsize to before computing the render pass.
  74861. * @param camera The camera to apply the render pass to.
  74862. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74863. * @param engine The engine which the post process will be applied. (default: current engine)
  74864. * @param reusable If the post process can be reused on the same frame. (default: false)
  74865. * @param textureType Type of textures used when performing the post process. (default: 0)
  74866. * @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)
  74867. */
  74868. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74869. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74870. if (blockCompilation === void 0) { blockCompilation = false; }
  74871. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74872. _this.blurSteps = blurSteps;
  74873. _this.onApplyObservable.add(function (effect) {
  74874. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74875. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74876. blurSteps.forEach(function (step, index) {
  74877. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74878. });
  74879. });
  74880. if (!blockCompilation) {
  74881. _this.updateEffect();
  74882. }
  74883. return _this;
  74884. }
  74885. /**
  74886. * Updates the effect with the current post process compile time values and recompiles the shader.
  74887. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74888. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74889. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74890. * @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
  74891. * @param onCompiled Called when the shader has been compiled.
  74892. * @param onError Called if there is an error when compiling a shader.
  74893. */
  74894. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74895. if (defines === void 0) { defines = null; }
  74896. if (uniforms === void 0) { uniforms = null; }
  74897. if (samplers === void 0) { samplers = null; }
  74898. if (!defines) {
  74899. defines = "";
  74900. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74901. }
  74902. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74903. };
  74904. return DepthOfFieldMergePostProcess;
  74905. }(BABYLON.PostProcess));
  74906. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74907. })(BABYLON || (BABYLON = {}));
  74908. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74909. var BABYLON;
  74910. (function (BABYLON) {
  74911. /**
  74912. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74913. */
  74914. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74915. __extends(CircleOfConfusionPostProcess, _super);
  74916. /**
  74917. * Creates a new instance CircleOfConfusionPostProcess
  74918. * @param name The name of the effect.
  74919. * @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.
  74920. * @param options The required width/height ratio to downsize to before computing the render pass.
  74921. * @param camera The camera to apply the render pass to.
  74922. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74923. * @param engine The engine which the post process will be applied. (default: current engine)
  74924. * @param reusable If the post process can be reused on the same frame. (default: false)
  74925. * @param textureType Type of textures used when performing the post process. (default: 0)
  74926. * @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)
  74927. */
  74928. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74929. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74930. if (blockCompilation === void 0) { blockCompilation = false; }
  74931. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74932. /**
  74933. * 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.
  74934. */
  74935. _this.lensSize = 50;
  74936. /**
  74937. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74938. */
  74939. _this.fStop = 1.4;
  74940. /**
  74941. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74942. */
  74943. _this.focusDistance = 2000;
  74944. /**
  74945. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74946. */
  74947. _this.focalLength = 50;
  74948. _this._depthTexture = null;
  74949. _this._depthTexture = depthTexture;
  74950. _this.onApplyObservable.add(function (effect) {
  74951. if (!_this._depthTexture) {
  74952. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74953. return;
  74954. }
  74955. effect.setTexture("depthSampler", _this._depthTexture);
  74956. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74957. var aperture = _this.lensSize / _this.fStop;
  74958. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74959. effect.setFloat('focusDistance', _this.focusDistance);
  74960. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74961. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74962. });
  74963. return _this;
  74964. }
  74965. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74966. /**
  74967. * 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.
  74968. */
  74969. set: function (value) {
  74970. this._depthTexture = value;
  74971. },
  74972. enumerable: true,
  74973. configurable: true
  74974. });
  74975. return CircleOfConfusionPostProcess;
  74976. }(BABYLON.PostProcess));
  74977. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74978. })(BABYLON || (BABYLON = {}));
  74979. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74980. var BABYLON;
  74981. (function (BABYLON) {
  74982. /**
  74983. * Specifies the level of max blur that should be applied when using the depth of field effect
  74984. */
  74985. var DepthOfFieldEffectBlurLevel;
  74986. (function (DepthOfFieldEffectBlurLevel) {
  74987. /**
  74988. * Subtle blur
  74989. */
  74990. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74991. /**
  74992. * Medium blur
  74993. */
  74994. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74995. /**
  74996. * Large blur
  74997. */
  74998. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74999. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75000. ;
  75001. /**
  75002. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75003. */
  75004. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75005. __extends(DepthOfFieldEffect, _super);
  75006. /**
  75007. * Creates a new instance DepthOfFieldEffect
  75008. * @param scene The scene the effect belongs to.
  75009. * @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.
  75010. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75011. * @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)
  75012. */
  75013. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75014. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75015. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75016. if (blockCompilation === void 0) { blockCompilation = false; }
  75017. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75018. return _this._effects;
  75019. }, true) || this;
  75020. /**
  75021. * Internal post processes in depth of field effect
  75022. */
  75023. _this._effects = [];
  75024. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75025. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75026. // 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)
  75027. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75028. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75029. _this._depthOfFieldBlurY = [];
  75030. _this._depthOfFieldBlurX = [];
  75031. var blurCount = 1;
  75032. var kernelSize = 15;
  75033. switch (blurLevel) {
  75034. case DepthOfFieldEffectBlurLevel.High: {
  75035. blurCount = 3;
  75036. kernelSize = 51;
  75037. break;
  75038. }
  75039. case DepthOfFieldEffectBlurLevel.Medium: {
  75040. blurCount = 2;
  75041. kernelSize = 31;
  75042. break;
  75043. }
  75044. default: {
  75045. kernelSize = 15;
  75046. blurCount = 1;
  75047. break;
  75048. }
  75049. }
  75050. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75051. var ratio = 1.0;
  75052. for (var i = 0; i < blurCount; i++) {
  75053. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75054. blurY.autoClear = false;
  75055. ratio = 0.75 / Math.pow(2, i);
  75056. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75057. blurX.autoClear = false;
  75058. _this._depthOfFieldBlurY.push(blurY);
  75059. _this._depthOfFieldBlurX.push(blurX);
  75060. }
  75061. // Set all post processes on the effect.
  75062. _this._effects = [_this._circleOfConfusion];
  75063. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75064. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75065. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75066. }
  75067. // Merge blurred images with original image based on circleOfConfusion
  75068. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75069. _this._dofMerge.autoClear = false;
  75070. _this._effects.push(_this._dofMerge);
  75071. return _this;
  75072. }
  75073. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75074. get: function () {
  75075. return this._circleOfConfusion.focalLength;
  75076. },
  75077. /**
  75078. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75079. */
  75080. set: function (value) {
  75081. this._circleOfConfusion.focalLength = value;
  75082. },
  75083. enumerable: true,
  75084. configurable: true
  75085. });
  75086. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75087. get: function () {
  75088. return this._circleOfConfusion.fStop;
  75089. },
  75090. /**
  75091. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75092. */
  75093. set: function (value) {
  75094. this._circleOfConfusion.fStop = value;
  75095. },
  75096. enumerable: true,
  75097. configurable: true
  75098. });
  75099. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75100. get: function () {
  75101. return this._circleOfConfusion.focusDistance;
  75102. },
  75103. /**
  75104. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75105. */
  75106. set: function (value) {
  75107. this._circleOfConfusion.focusDistance = value;
  75108. },
  75109. enumerable: true,
  75110. configurable: true
  75111. });
  75112. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75113. get: function () {
  75114. return this._circleOfConfusion.lensSize;
  75115. },
  75116. /**
  75117. * 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.
  75118. */
  75119. set: function (value) {
  75120. this._circleOfConfusion.lensSize = value;
  75121. },
  75122. enumerable: true,
  75123. configurable: true
  75124. });
  75125. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75126. /**
  75127. * 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.
  75128. */
  75129. set: function (value) {
  75130. this._circleOfConfusion.depthTexture = value;
  75131. },
  75132. enumerable: true,
  75133. configurable: true
  75134. });
  75135. /**
  75136. * Disposes each of the internal effects for a given camera.
  75137. * @param camera The camera to dispose the effect on.
  75138. */
  75139. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75140. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75141. this._effects[effectIndex].dispose(camera);
  75142. }
  75143. };
  75144. /**
  75145. * Internal
  75146. */
  75147. DepthOfFieldEffect.prototype._updateEffects = function () {
  75148. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75149. this._effects[effectIndex].updateEffect();
  75150. }
  75151. };
  75152. /**
  75153. * Internal
  75154. * @returns if all the contained post processes are ready.
  75155. */
  75156. DepthOfFieldEffect.prototype._isReady = function () {
  75157. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75158. if (!this._effects[effectIndex].isReady()) {
  75159. return false;
  75160. }
  75161. }
  75162. return true;
  75163. };
  75164. return DepthOfFieldEffect;
  75165. }(BABYLON.PostProcessRenderEffect));
  75166. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75167. })(BABYLON || (BABYLON = {}));
  75168. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75169. var BABYLON;
  75170. (function (BABYLON) {
  75171. /**
  75172. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75173. */
  75174. var BloomMergePostProcess = /** @class */ (function (_super) {
  75175. __extends(BloomMergePostProcess, _super);
  75176. /**
  75177. * Creates a new instance of @see BloomMergePostProcess
  75178. * @param name The name of the effect.
  75179. * @param originalFromInput Post process which's input will be used for the merge.
  75180. * @param blurred Blurred highlights post process which's output will be used.
  75181. * @param weight Weight of the bloom to be added to the original input.
  75182. * @param options The required width/height ratio to downsize to before computing the render pass.
  75183. * @param camera The camera to apply the render pass to.
  75184. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75185. * @param engine The engine which the post process will be applied. (default: current engine)
  75186. * @param reusable If the post process can be reused on the same frame. (default: false)
  75187. * @param textureType Type of textures used when performing the post process. (default: 0)
  75188. * @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)
  75189. */
  75190. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75191. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75192. if (blockCompilation === void 0) { blockCompilation = false; }
  75193. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75194. _this.weight = weight;
  75195. _this.onApplyObservable.add(function (effect) {
  75196. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75197. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75198. effect.setFloat("bloomWeight", _this.weight);
  75199. });
  75200. if (!blockCompilation) {
  75201. _this.updateEffect();
  75202. }
  75203. return _this;
  75204. }
  75205. return BloomMergePostProcess;
  75206. }(BABYLON.PostProcess));
  75207. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75208. })(BABYLON || (BABYLON = {}));
  75209. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75210. var BABYLON;
  75211. (function (BABYLON) {
  75212. /**
  75213. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  75214. */
  75215. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75216. __extends(ExtractHighlightsPostProcess, _super);
  75217. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75218. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75219. if (blockCompilation === void 0) { blockCompilation = false; }
  75220. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75221. /**
  75222. * The luminance threshold, pixels below this value will be set to black.
  75223. */
  75224. _this.threshold = 0.9;
  75225. /**
  75226. * Internal
  75227. */
  75228. _this._exposure = 1;
  75229. /**
  75230. * Post process which has the input texture to be used when performing highlight extraction
  75231. */
  75232. _this._inputPostProcess = null;
  75233. _this.onApplyObservable.add(function (effect) {
  75234. if (_this._inputPostProcess) {
  75235. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75236. }
  75237. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75238. effect.setFloat('exposure', _this._exposure);
  75239. });
  75240. return _this;
  75241. }
  75242. return ExtractHighlightsPostProcess;
  75243. }(BABYLON.PostProcess));
  75244. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75245. })(BABYLON || (BABYLON = {}));
  75246. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75247. var BABYLON;
  75248. (function (BABYLON) {
  75249. /**
  75250. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75251. */
  75252. var BloomEffect = /** @class */ (function (_super) {
  75253. __extends(BloomEffect, _super);
  75254. /**
  75255. * Creates a new instance of @see BloomEffect
  75256. * @param scene The scene the effect belongs to.
  75257. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75258. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75259. * @param bloomWeight The the strength of bloom.
  75260. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75261. * @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)
  75262. */
  75263. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75264. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75265. if (blockCompilation === void 0) { blockCompilation = false; }
  75266. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75267. return _this._effects;
  75268. }, true) || this;
  75269. _this.bloomScale = bloomScale;
  75270. /**
  75271. * Internal
  75272. */
  75273. _this._effects = [];
  75274. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75275. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75276. _this._blurX.alwaysForcePOT = true;
  75277. _this._blurX.autoClear = false;
  75278. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75279. _this._blurY.alwaysForcePOT = true;
  75280. _this._blurY.autoClear = false;
  75281. _this.kernel = bloomKernel;
  75282. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75283. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75284. _this._merge.autoClear = false;
  75285. _this._effects.push(_this._merge);
  75286. return _this;
  75287. }
  75288. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75289. /**
  75290. * The luminance threshold to find bright areas of the image to bloom.
  75291. */
  75292. get: function () {
  75293. return this._downscale.threshold;
  75294. },
  75295. set: function (value) {
  75296. this._downscale.threshold = value;
  75297. },
  75298. enumerable: true,
  75299. configurable: true
  75300. });
  75301. Object.defineProperty(BloomEffect.prototype, "weight", {
  75302. /**
  75303. * The strength of the bloom.
  75304. */
  75305. get: function () {
  75306. return this._merge.weight;
  75307. },
  75308. set: function (value) {
  75309. this._merge.weight = value;
  75310. },
  75311. enumerable: true,
  75312. configurable: true
  75313. });
  75314. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75315. /**
  75316. * Specifies the size of the bloom blur kernel, relative to the final output size
  75317. */
  75318. get: function () {
  75319. return this._blurX.kernel / this.bloomScale;
  75320. },
  75321. set: function (value) {
  75322. this._blurX.kernel = value * this.bloomScale;
  75323. this._blurY.kernel = value * this.bloomScale;
  75324. },
  75325. enumerable: true,
  75326. configurable: true
  75327. });
  75328. /**
  75329. * Disposes each of the internal effects for a given camera.
  75330. * @param camera The camera to dispose the effect on.
  75331. */
  75332. BloomEffect.prototype.disposeEffects = function (camera) {
  75333. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75334. this._effects[effectIndex].dispose(camera);
  75335. }
  75336. };
  75337. /**
  75338. * Internal
  75339. */
  75340. BloomEffect.prototype._updateEffects = function () {
  75341. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75342. this._effects[effectIndex].updateEffect();
  75343. }
  75344. };
  75345. /**
  75346. * Internal
  75347. * @returns if all the contained post processes are ready.
  75348. */
  75349. BloomEffect.prototype._isReady = function () {
  75350. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75351. if (!this._effects[effectIndex].isReady()) {
  75352. return false;
  75353. }
  75354. }
  75355. return true;
  75356. };
  75357. return BloomEffect;
  75358. }(BABYLON.PostProcessRenderEffect));
  75359. BABYLON.BloomEffect = BloomEffect;
  75360. })(BABYLON || (BABYLON = {}));
  75361. //# sourceMappingURL=babylon.bloomEffect.js.map
  75362. var BABYLON;
  75363. (function (BABYLON) {
  75364. /**
  75365. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75366. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75367. */
  75368. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75369. __extends(DefaultRenderingPipeline, _super);
  75370. /**
  75371. * @constructor
  75372. * @param {string} name - The rendering pipeline name
  75373. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75374. * @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)
  75375. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75376. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75377. */
  75378. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75379. if (automaticBuild === void 0) { automaticBuild = true; }
  75380. var _this = _super.call(this, scene.getEngine(), name) || this;
  75381. _this._originalCameras = [];
  75382. /**
  75383. * ID of the sharpen post process,
  75384. */
  75385. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75386. /**
  75387. * ID of the image processing post process;
  75388. */
  75389. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75390. /**
  75391. * ID of the Fast Approximate Anti-Aliasing post process;
  75392. */
  75393. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75394. /**
  75395. * ID of the chromatic aberration post process,
  75396. */
  75397. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75398. /**
  75399. * ID of the grain post process
  75400. */
  75401. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75402. /**
  75403. * Animations which can be used to tweak settings over a period of time
  75404. */
  75405. _this.animations = [];
  75406. _this._imageProcessingConfigurationObserver = null;
  75407. // Values
  75408. _this._sharpenEnabled = false;
  75409. _this._bloomEnabled = false;
  75410. _this._depthOfFieldEnabled = false;
  75411. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75412. _this._fxaaEnabled = false;
  75413. _this._imageProcessingEnabled = true;
  75414. _this._bloomScale = 0.5;
  75415. _this._chromaticAberrationEnabled = false;
  75416. _this._grainEnabled = false;
  75417. _this._buildAllowed = true;
  75418. _this._resizeObserver = null;
  75419. _this._hardwareScaleLevel = 1.0;
  75420. _this._bloomKernel = 64;
  75421. /**
  75422. * Specifies the weight of the bloom in the final rendering
  75423. */
  75424. _this._bloomWeight = 0.15;
  75425. /**
  75426. * Specifies the luma threshold for the area that will be blurred by the bloom
  75427. */
  75428. _this._bloomThreshold = 0.9;
  75429. _this._samples = 1;
  75430. _this._hasCleared = false;
  75431. _this._prevPostProcess = null;
  75432. _this._prevPrevPostProcess = null;
  75433. _this._cameras = cameras || [];
  75434. _this._originalCameras = _this._cameras.slice();
  75435. _this._buildAllowed = automaticBuild;
  75436. // Initialize
  75437. _this._scene = scene;
  75438. var caps = _this._scene.getEngine().getCaps();
  75439. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75440. // Misc
  75441. if (_this._hdr) {
  75442. if (caps.textureHalfFloatRender) {
  75443. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75444. }
  75445. else if (caps.textureFloatRender) {
  75446. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75447. }
  75448. }
  75449. else {
  75450. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75451. }
  75452. // Attach
  75453. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75454. var engine = _this._scene.getEngine();
  75455. // Create post processes before hand so they can be modified before enabled.
  75456. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75457. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75458. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75459. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75460. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75461. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75462. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75463. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75464. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75465. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75466. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75467. _this.bloomKernel = _this.bloomKernel;
  75468. });
  75469. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75470. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75471. });
  75472. _this._buildPipeline();
  75473. return _this;
  75474. }
  75475. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75476. get: function () {
  75477. return this._sharpenEnabled;
  75478. },
  75479. /**
  75480. * Enable or disable the sharpen process from the pipeline
  75481. */
  75482. set: function (enabled) {
  75483. if (this._sharpenEnabled === enabled) {
  75484. return;
  75485. }
  75486. this._sharpenEnabled = enabled;
  75487. this._buildPipeline();
  75488. },
  75489. enumerable: true,
  75490. configurable: true
  75491. });
  75492. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75493. /**
  75494. * Specifies the size of the bloom blur kernel, relative to the final output size
  75495. */
  75496. get: function () {
  75497. return this._bloomKernel;
  75498. },
  75499. set: function (value) {
  75500. this._bloomKernel = value;
  75501. this.bloom.kernel = value / this._hardwareScaleLevel;
  75502. },
  75503. enumerable: true,
  75504. configurable: true
  75505. });
  75506. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75507. get: function () {
  75508. return this._bloomWeight;
  75509. },
  75510. /**
  75511. * The strength of the bloom.
  75512. */
  75513. set: function (value) {
  75514. if (this._bloomWeight === value) {
  75515. return;
  75516. }
  75517. this.bloom.weight = value;
  75518. this._bloomWeight = value;
  75519. },
  75520. enumerable: true,
  75521. configurable: true
  75522. });
  75523. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75524. get: function () {
  75525. return this._bloomThreshold;
  75526. },
  75527. /**
  75528. * The strength of the bloom.
  75529. */
  75530. set: function (value) {
  75531. if (this._bloomThreshold === value) {
  75532. return;
  75533. }
  75534. this.bloom.threshold = value;
  75535. this._bloomThreshold = value;
  75536. },
  75537. enumerable: true,
  75538. configurable: true
  75539. });
  75540. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75541. get: function () {
  75542. return this._bloomScale;
  75543. },
  75544. /**
  75545. * The scale of the bloom, lower value will provide better performance.
  75546. */
  75547. set: function (value) {
  75548. if (this._bloomScale === value) {
  75549. return;
  75550. }
  75551. this._bloomScale = value;
  75552. // recreate bloom and dispose old as this setting is not dynamic
  75553. this._rebuildBloom();
  75554. this._buildPipeline();
  75555. },
  75556. enumerable: true,
  75557. configurable: true
  75558. });
  75559. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75560. get: function () {
  75561. return this._bloomEnabled;
  75562. },
  75563. /**
  75564. * Enable or disable the bloom from the pipeline
  75565. */
  75566. set: function (enabled) {
  75567. if (this._bloomEnabled === enabled) {
  75568. return;
  75569. }
  75570. this._bloomEnabled = enabled;
  75571. this._buildPipeline();
  75572. },
  75573. enumerable: true,
  75574. configurable: true
  75575. });
  75576. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75577. // recreate bloom and dispose old as this setting is not dynamic
  75578. var oldBloom = this.bloom;
  75579. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75580. this.bloom.threshold = oldBloom.threshold;
  75581. for (var i = 0; i < this._cameras.length; i++) {
  75582. oldBloom.disposeEffects(this._cameras[i]);
  75583. }
  75584. };
  75585. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75586. /**
  75587. * If the depth of field is enabled.
  75588. */
  75589. get: function () {
  75590. return this._depthOfFieldEnabled;
  75591. },
  75592. set: function (enabled) {
  75593. if (this._depthOfFieldEnabled === enabled) {
  75594. return;
  75595. }
  75596. this._depthOfFieldEnabled = enabled;
  75597. this._buildPipeline();
  75598. },
  75599. enumerable: true,
  75600. configurable: true
  75601. });
  75602. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75603. /**
  75604. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75605. */
  75606. get: function () {
  75607. return this._depthOfFieldBlurLevel;
  75608. },
  75609. set: function (value) {
  75610. if (this._depthOfFieldBlurLevel === value) {
  75611. return;
  75612. }
  75613. this._depthOfFieldBlurLevel = value;
  75614. // recreate dof and dispose old as this setting is not dynamic
  75615. var oldDof = this.depthOfField;
  75616. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75617. this.depthOfField.focalLength = oldDof.focalLength;
  75618. this.depthOfField.focusDistance = oldDof.focusDistance;
  75619. this.depthOfField.fStop = oldDof.fStop;
  75620. this.depthOfField.lensSize = oldDof.lensSize;
  75621. for (var i = 0; i < this._cameras.length; i++) {
  75622. oldDof.disposeEffects(this._cameras[i]);
  75623. }
  75624. this._buildPipeline();
  75625. },
  75626. enumerable: true,
  75627. configurable: true
  75628. });
  75629. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75630. get: function () {
  75631. return this._fxaaEnabled;
  75632. },
  75633. /**
  75634. * If the anti aliasing is enabled.
  75635. */
  75636. set: function (enabled) {
  75637. if (this._fxaaEnabled === enabled) {
  75638. return;
  75639. }
  75640. this._fxaaEnabled = enabled;
  75641. this._buildPipeline();
  75642. },
  75643. enumerable: true,
  75644. configurable: true
  75645. });
  75646. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75647. get: function () {
  75648. return this._samples;
  75649. },
  75650. /**
  75651. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75652. */
  75653. set: function (sampleCount) {
  75654. if (this._samples === sampleCount) {
  75655. return;
  75656. }
  75657. this._samples = sampleCount;
  75658. this._buildPipeline();
  75659. },
  75660. enumerable: true,
  75661. configurable: true
  75662. });
  75663. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75664. get: function () {
  75665. return this._imageProcessingEnabled;
  75666. },
  75667. /**
  75668. * If image processing is enabled.
  75669. */
  75670. set: function (enabled) {
  75671. if (this._imageProcessingEnabled === enabled) {
  75672. return;
  75673. }
  75674. this._imageProcessingEnabled = enabled;
  75675. this._buildPipeline();
  75676. },
  75677. enumerable: true,
  75678. configurable: true
  75679. });
  75680. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75681. get: function () {
  75682. return this._chromaticAberrationEnabled;
  75683. },
  75684. /**
  75685. * Enable or disable the chromaticAberration process from the pipeline
  75686. */
  75687. set: function (enabled) {
  75688. if (this._chromaticAberrationEnabled === enabled) {
  75689. return;
  75690. }
  75691. this._chromaticAberrationEnabled = enabled;
  75692. this._buildPipeline();
  75693. },
  75694. enumerable: true,
  75695. configurable: true
  75696. });
  75697. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75698. get: function () {
  75699. return this._grainEnabled;
  75700. },
  75701. /**
  75702. * Enable or disable the grain process from the pipeline
  75703. */
  75704. set: function (enabled) {
  75705. if (this._grainEnabled === enabled) {
  75706. return;
  75707. }
  75708. this._grainEnabled = enabled;
  75709. this._buildPipeline();
  75710. },
  75711. enumerable: true,
  75712. configurable: true
  75713. });
  75714. /**
  75715. * Force the compilation of the entire pipeline.
  75716. */
  75717. DefaultRenderingPipeline.prototype.prepare = function () {
  75718. var previousState = this._buildAllowed;
  75719. this._buildAllowed = true;
  75720. this._buildPipeline();
  75721. this._buildAllowed = previousState;
  75722. };
  75723. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75724. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75725. if (this._hasCleared) {
  75726. postProcess.autoClear = false;
  75727. }
  75728. else {
  75729. postProcess.autoClear = true;
  75730. this._scene.autoClear = false;
  75731. this._hasCleared = true;
  75732. }
  75733. if (!skipTextureSharing) {
  75734. if (this._prevPrevPostProcess) {
  75735. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75736. }
  75737. else {
  75738. postProcess.useOwnOutput();
  75739. }
  75740. if (this._prevPostProcess) {
  75741. this._prevPrevPostProcess = this._prevPostProcess;
  75742. }
  75743. this._prevPostProcess = postProcess;
  75744. }
  75745. };
  75746. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75747. var _this = this;
  75748. if (!this._buildAllowed) {
  75749. return;
  75750. }
  75751. this._scene.autoClear = true;
  75752. var engine = this._scene.getEngine();
  75753. this._disposePostProcesses();
  75754. if (this._cameras !== null) {
  75755. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75756. // get back cameras to be used to reattach pipeline
  75757. this._cameras = this._originalCameras.slice();
  75758. }
  75759. this._reset();
  75760. this._prevPostProcess = null;
  75761. this._prevPrevPostProcess = null;
  75762. this._hasCleared = false;
  75763. if (this.depthOfFieldEnabled) {
  75764. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75765. this.depthOfField.depthTexture = depthTexture;
  75766. if (!this.depthOfField._isReady()) {
  75767. this.depthOfField._updateEffects();
  75768. }
  75769. this.addEffect(this.depthOfField);
  75770. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75771. }
  75772. if (this.bloomEnabled) {
  75773. if (!this.bloom._isReady()) {
  75774. this.bloom._updateEffects();
  75775. }
  75776. this.addEffect(this.bloom);
  75777. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75778. }
  75779. if (this._imageProcessingEnabled) {
  75780. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75781. if (this._hdr) {
  75782. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75783. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75784. }
  75785. else {
  75786. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75787. }
  75788. }
  75789. if (this.sharpenEnabled) {
  75790. if (!this.sharpen.isReady()) {
  75791. this.sharpen.updateEffect();
  75792. }
  75793. this.addEffect(this._sharpenEffect);
  75794. this._setAutoClearAndTextureSharing(this.sharpen);
  75795. }
  75796. if (this.grainEnabled) {
  75797. if (!this.grain.isReady()) {
  75798. this.grain.updateEffect();
  75799. }
  75800. this.addEffect(this._grainEffect);
  75801. this._setAutoClearAndTextureSharing(this.grain);
  75802. }
  75803. if (this.chromaticAberrationEnabled) {
  75804. if (!this.chromaticAberration.isReady()) {
  75805. this.chromaticAberration.updateEffect();
  75806. }
  75807. this.addEffect(this._chromaticAberrationEffect);
  75808. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75809. }
  75810. if (this.fxaaEnabled) {
  75811. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75812. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75813. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75814. }
  75815. if (this._cameras !== null) {
  75816. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75817. }
  75818. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75819. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75820. }
  75821. };
  75822. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75823. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75824. for (var i = 0; i < this._cameras.length; i++) {
  75825. var camera = this._cameras[i];
  75826. if (this.imageProcessing) {
  75827. this.imageProcessing.dispose(camera);
  75828. }
  75829. if (this.fxaa) {
  75830. this.fxaa.dispose(camera);
  75831. }
  75832. // These are created in the constructor and should not be disposed on every pipeline change
  75833. if (disposeNonRecreated) {
  75834. if (this.sharpen) {
  75835. this.sharpen.dispose(camera);
  75836. }
  75837. if (this.depthOfField) {
  75838. this.depthOfField.disposeEffects(camera);
  75839. }
  75840. if (this.bloom) {
  75841. this.bloom.disposeEffects(camera);
  75842. }
  75843. if (this.chromaticAberration) {
  75844. this.chromaticAberration.dispose(camera);
  75845. }
  75846. if (this.grain) {
  75847. this.grain.dispose(camera);
  75848. }
  75849. }
  75850. }
  75851. this.imageProcessing = null;
  75852. this.fxaa = null;
  75853. if (disposeNonRecreated) {
  75854. this.sharpen = null;
  75855. this._sharpenEffect = null;
  75856. this.depthOfField = null;
  75857. this.bloom = null;
  75858. this.chromaticAberration = null;
  75859. this._chromaticAberrationEffect = null;
  75860. this.grain = null;
  75861. this._grainEffect = null;
  75862. }
  75863. };
  75864. /**
  75865. * Dispose of the pipeline and stop all post processes
  75866. */
  75867. DefaultRenderingPipeline.prototype.dispose = function () {
  75868. this._disposePostProcesses(true);
  75869. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75870. this._scene.autoClear = true;
  75871. if (this._resizeObserver) {
  75872. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75873. this._resizeObserver = null;
  75874. }
  75875. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75876. _super.prototype.dispose.call(this);
  75877. };
  75878. /**
  75879. * Serialize the rendering pipeline (Used when exporting)
  75880. * @returns the serialized object
  75881. */
  75882. DefaultRenderingPipeline.prototype.serialize = function () {
  75883. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75884. serializationObject.customType = "DefaultRenderingPipeline";
  75885. return serializationObject;
  75886. };
  75887. /**
  75888. * Parse the serialized pipeline
  75889. * @param source Source pipeline.
  75890. * @param scene The scene to load the pipeline to.
  75891. * @param rootUrl The URL of the serialized pipeline.
  75892. * @returns An instantiated pipeline from the serialized object.
  75893. */
  75894. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75895. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75896. };
  75897. __decorate([
  75898. BABYLON.serialize()
  75899. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75900. __decorate([
  75901. BABYLON.serialize()
  75902. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75903. __decorate([
  75904. BABYLON.serialize()
  75905. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75906. __decorate([
  75907. BABYLON.serialize()
  75908. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75909. __decorate([
  75910. BABYLON.serialize()
  75911. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75912. __decorate([
  75913. BABYLON.serialize()
  75914. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75915. __decorate([
  75916. BABYLON.serialize()
  75917. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75918. __decorate([
  75919. BABYLON.serialize()
  75920. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75921. __decorate([
  75922. BABYLON.serialize()
  75923. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75924. __decorate([
  75925. BABYLON.serialize()
  75926. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75927. __decorate([
  75928. BABYLON.serialize()
  75929. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75930. __decorate([
  75931. BABYLON.serialize()
  75932. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75933. __decorate([
  75934. BABYLON.serialize()
  75935. ], DefaultRenderingPipeline.prototype, "samples", null);
  75936. __decorate([
  75937. BABYLON.serialize()
  75938. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75939. __decorate([
  75940. BABYLON.serialize()
  75941. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75942. __decorate([
  75943. BABYLON.serialize()
  75944. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75945. return DefaultRenderingPipeline;
  75946. }(BABYLON.PostProcessRenderPipeline));
  75947. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75948. })(BABYLON || (BABYLON = {}));
  75949. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75950. var BABYLON;
  75951. (function (BABYLON) {
  75952. /**
  75953. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75954. */
  75955. var GeometryBufferRenderer = /** @class */ (function () {
  75956. /**
  75957. * Creates a new G Buffer for the scene
  75958. * @param scene The scene the buffer belongs to
  75959. * @param ratio How big is the buffer related to the main canvas.
  75960. */
  75961. function GeometryBufferRenderer(scene, ratio) {
  75962. if (ratio === void 0) { ratio = 1; }
  75963. this._enablePosition = false;
  75964. this._scene = scene;
  75965. this._ratio = ratio;
  75966. // Render target
  75967. this._createRenderTargets();
  75968. }
  75969. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75970. /**
  75971. * Set the render list (meshes to be rendered) used in the G buffer.
  75972. */
  75973. set: function (meshes) {
  75974. this._multiRenderTarget.renderList = meshes;
  75975. },
  75976. enumerable: true,
  75977. configurable: true
  75978. });
  75979. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75980. /**
  75981. * Gets wether or not G buffer are supported by the running hardware.
  75982. * This requires draw buffer supports
  75983. */
  75984. get: function () {
  75985. return this._multiRenderTarget.isSupported;
  75986. },
  75987. enumerable: true,
  75988. configurable: true
  75989. });
  75990. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75991. /**
  75992. * Gets wether or not position are enabled for the G buffer.
  75993. */
  75994. get: function () {
  75995. return this._enablePosition;
  75996. },
  75997. /**
  75998. * Sets wether or not position are enabled for the G buffer.
  75999. */
  76000. set: function (enable) {
  76001. this._enablePosition = enable;
  76002. this.dispose();
  76003. this._createRenderTargets();
  76004. },
  76005. enumerable: true,
  76006. configurable: true
  76007. });
  76008. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76009. /**
  76010. * Gets the scene associated with the buffer.
  76011. */
  76012. get: function () {
  76013. return this._scene;
  76014. },
  76015. enumerable: true,
  76016. configurable: true
  76017. });
  76018. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76019. /**
  76020. * Gets the ratio used by the buffer during its creation.
  76021. * How big is the buffer related to the main canvas.
  76022. */
  76023. get: function () {
  76024. return this._ratio;
  76025. },
  76026. enumerable: true,
  76027. configurable: true
  76028. });
  76029. /**
  76030. * Checks wether everything is ready to render a submesh to the G buffer.
  76031. * @param subMesh the submesh to check readiness for
  76032. * @param useInstances is the mesh drawn using instance or not
  76033. * @returns true if ready otherwise false
  76034. */
  76035. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76036. var material = subMesh.getMaterial();
  76037. if (material && material.disableDepthWrite) {
  76038. return false;
  76039. }
  76040. var defines = [];
  76041. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76042. var mesh = subMesh.getMesh();
  76043. // Alpha test
  76044. if (material && material.needAlphaTesting()) {
  76045. defines.push("#define ALPHATEST");
  76046. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76047. attribs.push(BABYLON.VertexBuffer.UVKind);
  76048. defines.push("#define UV1");
  76049. }
  76050. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76051. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76052. defines.push("#define UV2");
  76053. }
  76054. }
  76055. // Buffers
  76056. if (this._enablePosition) {
  76057. defines.push("#define POSITION");
  76058. }
  76059. // Bones
  76060. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76061. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76062. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76063. if (mesh.numBoneInfluencers > 4) {
  76064. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76065. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76066. }
  76067. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76068. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76069. }
  76070. else {
  76071. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76072. }
  76073. // Instances
  76074. if (useInstances) {
  76075. defines.push("#define INSTANCES");
  76076. attribs.push("world0");
  76077. attribs.push("world1");
  76078. attribs.push("world2");
  76079. attribs.push("world3");
  76080. }
  76081. // Get correct effect
  76082. var join = defines.join("\n");
  76083. if (this._cachedDefines !== join) {
  76084. this._cachedDefines = join;
  76085. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76086. }
  76087. return this._effect.isReady();
  76088. };
  76089. /**
  76090. * Gets the current underlying G Buffer.
  76091. * @returns the buffer
  76092. */
  76093. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76094. return this._multiRenderTarget;
  76095. };
  76096. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76097. /**
  76098. * Gets the number of samples used to render the buffer (anti aliasing).
  76099. */
  76100. get: function () {
  76101. return this._multiRenderTarget.samples;
  76102. },
  76103. /**
  76104. * Sets the number of samples used to render the buffer (anti aliasing).
  76105. */
  76106. set: function (value) {
  76107. this._multiRenderTarget.samples = value;
  76108. },
  76109. enumerable: true,
  76110. configurable: true
  76111. });
  76112. /**
  76113. * Disposes the renderer and frees up associated resources.
  76114. */
  76115. GeometryBufferRenderer.prototype.dispose = function () {
  76116. this.getGBuffer().dispose();
  76117. };
  76118. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76119. var _this = this;
  76120. var engine = this._scene.getEngine();
  76121. var count = this._enablePosition ? 3 : 2;
  76122. 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 });
  76123. if (!this.isSupported) {
  76124. return;
  76125. }
  76126. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76127. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76128. this._multiRenderTarget.refreshRate = 1;
  76129. this._multiRenderTarget.renderParticles = false;
  76130. this._multiRenderTarget.renderList = null;
  76131. // set default depth value to 1.0 (far away)
  76132. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76133. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76134. });
  76135. // Custom render function
  76136. var renderSubMesh = function (subMesh) {
  76137. var mesh = subMesh.getRenderingMesh();
  76138. var scene = _this._scene;
  76139. var engine = scene.getEngine();
  76140. var material = subMesh.getMaterial();
  76141. if (!material) {
  76142. return;
  76143. }
  76144. // Culling
  76145. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76146. // Managing instances
  76147. var batch = mesh._getInstancesRenderList(subMesh._id);
  76148. if (batch.mustReturn) {
  76149. return;
  76150. }
  76151. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76152. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76153. engine.enableEffect(_this._effect);
  76154. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76155. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76156. _this._effect.setMatrix("view", scene.getViewMatrix());
  76157. // Alpha test
  76158. if (material && material.needAlphaTesting()) {
  76159. var alphaTexture = material.getAlphaTestTexture();
  76160. if (alphaTexture) {
  76161. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76162. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76163. }
  76164. }
  76165. // Bones
  76166. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76167. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76168. }
  76169. // Draw
  76170. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76171. }
  76172. };
  76173. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76174. var index;
  76175. if (depthOnlySubMeshes.length) {
  76176. engine.setColorWrite(false);
  76177. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76178. renderSubMesh(depthOnlySubMeshes.data[index]);
  76179. }
  76180. engine.setColorWrite(true);
  76181. }
  76182. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76183. renderSubMesh(opaqueSubMeshes.data[index]);
  76184. }
  76185. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76186. renderSubMesh(alphaTestSubMeshes.data[index]);
  76187. }
  76188. };
  76189. };
  76190. return GeometryBufferRenderer;
  76191. }());
  76192. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76193. })(BABYLON || (BABYLON = {}));
  76194. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76195. var BABYLON;
  76196. (function (BABYLON) {
  76197. var RefractionPostProcess = /** @class */ (function (_super) {
  76198. __extends(RefractionPostProcess, _super);
  76199. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76200. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76201. _this.color = color;
  76202. _this.depth = depth;
  76203. _this.colorLevel = colorLevel;
  76204. _this._ownRefractionTexture = true;
  76205. _this.onActivateObservable.add(function (cam) {
  76206. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76207. });
  76208. _this.onApplyObservable.add(function (effect) {
  76209. effect.setColor3("baseColor", _this.color);
  76210. effect.setFloat("depth", _this.depth);
  76211. effect.setFloat("colorLevel", _this.colorLevel);
  76212. effect.setTexture("refractionSampler", _this._refTexture);
  76213. });
  76214. return _this;
  76215. }
  76216. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76217. /**
  76218. * Gets or sets the refraction texture
  76219. * Please note that you are responsible for disposing the texture if you set it manually
  76220. */
  76221. get: function () {
  76222. return this._refTexture;
  76223. },
  76224. set: function (value) {
  76225. if (this._refTexture && this._ownRefractionTexture) {
  76226. this._refTexture.dispose();
  76227. }
  76228. this._refTexture = value;
  76229. this._ownRefractionTexture = false;
  76230. },
  76231. enumerable: true,
  76232. configurable: true
  76233. });
  76234. // Methods
  76235. RefractionPostProcess.prototype.dispose = function (camera) {
  76236. if (this._refTexture && this._ownRefractionTexture) {
  76237. this._refTexture.dispose();
  76238. this._refTexture = null;
  76239. }
  76240. _super.prototype.dispose.call(this, camera);
  76241. };
  76242. return RefractionPostProcess;
  76243. }(BABYLON.PostProcess));
  76244. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76245. })(BABYLON || (BABYLON = {}));
  76246. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76247. var BABYLON;
  76248. (function (BABYLON) {
  76249. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76250. __extends(BlackAndWhitePostProcess, _super);
  76251. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76252. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76253. _this.degree = 1;
  76254. _this.onApplyObservable.add(function (effect) {
  76255. effect.setFloat("degree", _this.degree);
  76256. });
  76257. return _this;
  76258. }
  76259. return BlackAndWhitePostProcess;
  76260. }(BABYLON.PostProcess));
  76261. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76262. })(BABYLON || (BABYLON = {}));
  76263. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76264. var BABYLON;
  76265. (function (BABYLON) {
  76266. /**
  76267. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76268. * input texture to perform effects such as edge detection or sharpening
  76269. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76270. */
  76271. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76272. __extends(ConvolutionPostProcess, _super);
  76273. /**
  76274. * Creates a new instance ConvolutionPostProcess
  76275. * @param name The name of the effect.
  76276. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76277. * @param options The required width/height ratio to downsize to before computing the render pass.
  76278. * @param camera The camera to apply the render pass to.
  76279. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76280. * @param engine The engine which the post process will be applied. (default: current engine)
  76281. * @param reusable If the post process can be reused on the same frame. (default: false)
  76282. * @param textureType Type of textures used when performing the post process. (default: 0)
  76283. */
  76284. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76285. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76286. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76287. _this.kernel = kernel;
  76288. _this.onApply = function (effect) {
  76289. effect.setFloat2("screenSize", _this.width, _this.height);
  76290. effect.setArray("kernel", _this.kernel);
  76291. };
  76292. return _this;
  76293. }
  76294. // Statics
  76295. /**
  76296. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76297. */
  76298. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76299. /**
  76300. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76301. */
  76302. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76303. /**
  76304. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76305. */
  76306. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76307. /**
  76308. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76309. */
  76310. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76311. /**
  76312. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76313. */
  76314. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76315. /**
  76316. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76317. */
  76318. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76319. return ConvolutionPostProcess;
  76320. }(BABYLON.PostProcess));
  76321. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76322. })(BABYLON || (BABYLON = {}));
  76323. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76324. var BABYLON;
  76325. (function (BABYLON) {
  76326. var FilterPostProcess = /** @class */ (function (_super) {
  76327. __extends(FilterPostProcess, _super);
  76328. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76329. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76330. _this.kernelMatrix = kernelMatrix;
  76331. _this.onApply = function (effect) {
  76332. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76333. };
  76334. return _this;
  76335. }
  76336. return FilterPostProcess;
  76337. }(BABYLON.PostProcess));
  76338. BABYLON.FilterPostProcess = FilterPostProcess;
  76339. })(BABYLON || (BABYLON = {}));
  76340. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76341. var BABYLON;
  76342. (function (BABYLON) {
  76343. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76344. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76345. __extends(VolumetricLightScatteringPostProcess, _super);
  76346. /**
  76347. * @constructor
  76348. * @param {string} name - The post-process name
  76349. * @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)
  76350. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76351. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76352. * @param {number} samples - The post-process quality, default 100
  76353. * @param {number} samplingMode - The post-process filtering mode
  76354. * @param {BABYLON.Engine} engine - The babylon engine
  76355. * @param {boolean} reusable - If the post-process is reusable
  76356. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76357. */
  76358. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76359. if (samples === void 0) { samples = 100; }
  76360. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76361. 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;
  76362. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76363. /**
  76364. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76365. */
  76366. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76367. /**
  76368. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76369. */
  76370. _this.useCustomMeshPosition = false;
  76371. /**
  76372. * If the post-process should inverse the light scattering direction
  76373. */
  76374. _this.invert = true;
  76375. /**
  76376. * Array containing the excluded meshes not rendered in the internal pass
  76377. */
  76378. _this.excludedMeshes = new Array();
  76379. /**
  76380. * Controls the overall intensity of the post-process
  76381. */
  76382. _this.exposure = 0.3;
  76383. /**
  76384. * Dissipates each sample's contribution in range [0, 1]
  76385. */
  76386. _this.decay = 0.96815;
  76387. /**
  76388. * Controls the overall intensity of each sample
  76389. */
  76390. _this.weight = 0.58767;
  76391. /**
  76392. * Controls the density of each sample
  76393. */
  76394. _this.density = 0.926;
  76395. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76396. engine = scene.getEngine();
  76397. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76398. // Configure mesh
  76399. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76400. // Configure
  76401. _this._createPass(scene, ratio.passRatio || ratio);
  76402. _this.onActivate = function (camera) {
  76403. if (!_this.isSupported) {
  76404. _this.dispose(camera);
  76405. }
  76406. _this.onActivate = null;
  76407. };
  76408. _this.onApplyObservable.add(function (effect) {
  76409. _this._updateMeshScreenCoordinates(scene);
  76410. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76411. effect.setFloat("exposure", _this.exposure);
  76412. effect.setFloat("decay", _this.decay);
  76413. effect.setFloat("weight", _this.weight);
  76414. effect.setFloat("density", _this.density);
  76415. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76416. });
  76417. return _this;
  76418. }
  76419. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76420. get: function () {
  76421. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76422. return false;
  76423. },
  76424. set: function (useDiffuseColor) {
  76425. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76426. },
  76427. enumerable: true,
  76428. configurable: true
  76429. });
  76430. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76431. return "VolumetricLightScatteringPostProcess";
  76432. };
  76433. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76434. var mesh = subMesh.getMesh();
  76435. // Render this.mesh as default
  76436. if (mesh === this.mesh && mesh.material) {
  76437. return mesh.material.isReady(mesh);
  76438. }
  76439. var defines = [];
  76440. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76441. var material = subMesh.getMaterial();
  76442. // Alpha test
  76443. if (material) {
  76444. if (material.needAlphaTesting()) {
  76445. defines.push("#define ALPHATEST");
  76446. }
  76447. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76448. attribs.push(BABYLON.VertexBuffer.UVKind);
  76449. defines.push("#define UV1");
  76450. }
  76451. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76452. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76453. defines.push("#define UV2");
  76454. }
  76455. }
  76456. // Bones
  76457. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76458. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76459. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76460. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76461. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76462. }
  76463. else {
  76464. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76465. }
  76466. // Instances
  76467. if (useInstances) {
  76468. defines.push("#define INSTANCES");
  76469. attribs.push("world0");
  76470. attribs.push("world1");
  76471. attribs.push("world2");
  76472. attribs.push("world3");
  76473. }
  76474. // Get correct effect
  76475. var join = defines.join("\n");
  76476. if (this._cachedDefines !== join) {
  76477. this._cachedDefines = join;
  76478. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76479. }
  76480. return this._volumetricLightScatteringPass.isReady();
  76481. };
  76482. /**
  76483. * Sets the new light position for light scattering effect
  76484. * @param {BABYLON.Vector3} The new custom light position
  76485. */
  76486. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76487. this.customMeshPosition = position;
  76488. };
  76489. /**
  76490. * Returns the light position for light scattering effect
  76491. * @return {BABYLON.Vector3} The custom light position
  76492. */
  76493. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76494. return this.customMeshPosition;
  76495. };
  76496. /**
  76497. * Disposes the internal assets and detaches the post-process from the camera
  76498. */
  76499. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76500. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76501. if (rttIndex !== -1) {
  76502. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76503. }
  76504. this._volumetricLightScatteringRTT.dispose();
  76505. _super.prototype.dispose.call(this, camera);
  76506. };
  76507. /**
  76508. * Returns the render target texture used by the post-process
  76509. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76510. */
  76511. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76512. return this._volumetricLightScatteringRTT;
  76513. };
  76514. // Private methods
  76515. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76516. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76517. return true;
  76518. }
  76519. return false;
  76520. };
  76521. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76522. var _this = this;
  76523. var engine = scene.getEngine();
  76524. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76525. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76526. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76527. this._volumetricLightScatteringRTT.renderList = null;
  76528. this._volumetricLightScatteringRTT.renderParticles = false;
  76529. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76530. var camera = this.getCamera();
  76531. if (camera) {
  76532. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76533. }
  76534. else {
  76535. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76536. }
  76537. // Custom render function for submeshes
  76538. var renderSubMesh = function (subMesh) {
  76539. var mesh = subMesh.getRenderingMesh();
  76540. if (_this._meshExcluded(mesh)) {
  76541. return;
  76542. }
  76543. var material = subMesh.getMaterial();
  76544. if (!material) {
  76545. return;
  76546. }
  76547. var scene = mesh.getScene();
  76548. var engine = scene.getEngine();
  76549. // Culling
  76550. engine.setState(material.backFaceCulling);
  76551. // Managing instances
  76552. var batch = mesh._getInstancesRenderList(subMesh._id);
  76553. if (batch.mustReturn) {
  76554. return;
  76555. }
  76556. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76557. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76558. var effect = _this._volumetricLightScatteringPass;
  76559. if (mesh === _this.mesh) {
  76560. if (subMesh.effect) {
  76561. effect = subMesh.effect;
  76562. }
  76563. else {
  76564. effect = material.getEffect();
  76565. }
  76566. }
  76567. engine.enableEffect(effect);
  76568. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76569. if (mesh === _this.mesh) {
  76570. material.bind(mesh.getWorldMatrix(), mesh);
  76571. }
  76572. else {
  76573. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76574. // Alpha test
  76575. if (material && material.needAlphaTesting()) {
  76576. var alphaTexture = material.getAlphaTestTexture();
  76577. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76578. if (alphaTexture) {
  76579. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76580. }
  76581. }
  76582. // Bones
  76583. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76584. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76585. }
  76586. }
  76587. // Draw
  76588. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76589. }
  76590. };
  76591. // Render target texture callbacks
  76592. var savedSceneClearColor;
  76593. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76594. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76595. savedSceneClearColor = scene.clearColor;
  76596. scene.clearColor = sceneClearColor;
  76597. });
  76598. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76599. scene.clearColor = savedSceneClearColor;
  76600. });
  76601. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76602. var engine = scene.getEngine();
  76603. var index;
  76604. if (depthOnlySubMeshes.length) {
  76605. engine.setColorWrite(false);
  76606. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76607. renderSubMesh(depthOnlySubMeshes.data[index]);
  76608. }
  76609. engine.setColorWrite(true);
  76610. }
  76611. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76612. renderSubMesh(opaqueSubMeshes.data[index]);
  76613. }
  76614. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76615. renderSubMesh(alphaTestSubMeshes.data[index]);
  76616. }
  76617. if (transparentSubMeshes.length) {
  76618. // Sort sub meshes
  76619. for (index = 0; index < transparentSubMeshes.length; index++) {
  76620. var submesh = transparentSubMeshes.data[index];
  76621. var boundingInfo = submesh.getBoundingInfo();
  76622. if (boundingInfo && scene.activeCamera) {
  76623. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76624. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76625. }
  76626. }
  76627. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76628. sortedArray.sort(function (a, b) {
  76629. // Alpha index first
  76630. if (a._alphaIndex > b._alphaIndex) {
  76631. return 1;
  76632. }
  76633. if (a._alphaIndex < b._alphaIndex) {
  76634. return -1;
  76635. }
  76636. // Then distance to camera
  76637. if (a._distanceToCamera < b._distanceToCamera) {
  76638. return 1;
  76639. }
  76640. if (a._distanceToCamera > b._distanceToCamera) {
  76641. return -1;
  76642. }
  76643. return 0;
  76644. });
  76645. // Render sub meshes
  76646. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76647. for (index = 0; index < sortedArray.length; index++) {
  76648. renderSubMesh(sortedArray[index]);
  76649. }
  76650. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76651. }
  76652. };
  76653. };
  76654. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76655. var transform = scene.getTransformMatrix();
  76656. var meshPosition;
  76657. if (this.useCustomMeshPosition) {
  76658. meshPosition = this.customMeshPosition;
  76659. }
  76660. else if (this.attachedNode) {
  76661. meshPosition = this.attachedNode.position;
  76662. }
  76663. else {
  76664. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76665. }
  76666. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76667. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76668. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76669. if (this.invert)
  76670. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76671. };
  76672. // Static methods
  76673. /**
  76674. * Creates a default mesh for the Volumeric Light Scattering post-process
  76675. * @param {string} The mesh name
  76676. * @param {BABYLON.Scene} The scene where to create the mesh
  76677. * @return {BABYLON.Mesh} the default mesh
  76678. */
  76679. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76680. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76681. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76682. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76683. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76684. mesh.material = material;
  76685. return mesh;
  76686. };
  76687. __decorate([
  76688. BABYLON.serializeAsVector3()
  76689. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76690. __decorate([
  76691. BABYLON.serialize()
  76692. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76693. __decorate([
  76694. BABYLON.serialize()
  76695. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76696. __decorate([
  76697. BABYLON.serializeAsMeshReference()
  76698. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76699. __decorate([
  76700. BABYLON.serialize()
  76701. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76702. __decorate([
  76703. BABYLON.serialize()
  76704. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76705. __decorate([
  76706. BABYLON.serialize()
  76707. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76708. __decorate([
  76709. BABYLON.serialize()
  76710. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76711. __decorate([
  76712. BABYLON.serialize()
  76713. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76714. return VolumetricLightScatteringPostProcess;
  76715. }(BABYLON.PostProcess));
  76716. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76717. })(BABYLON || (BABYLON = {}));
  76718. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76719. //
  76720. // This post-process allows the modification of rendered colors by using
  76721. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76722. //
  76723. // The object needs to be provided an url to a texture containing the color
  76724. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76725. // Use an image editing software to tweak the LUT to match your needs.
  76726. //
  76727. // For an example of a color LUT, see here:
  76728. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76729. // For explanations on color grading, see here:
  76730. // http://udn.epicgames.com/Three/ColorGrading.html
  76731. //
  76732. var BABYLON;
  76733. (function (BABYLON) {
  76734. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76735. __extends(ColorCorrectionPostProcess, _super);
  76736. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76737. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76738. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76739. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76740. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76741. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76742. _this.onApply = function (effect) {
  76743. effect.setTexture("colorTable", _this._colorTableTexture);
  76744. };
  76745. return _this;
  76746. }
  76747. return ColorCorrectionPostProcess;
  76748. }(BABYLON.PostProcess));
  76749. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76750. })(BABYLON || (BABYLON = {}));
  76751. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76752. var BABYLON;
  76753. (function (BABYLON) {
  76754. /** Defines operator used for tonemapping */
  76755. var TonemappingOperator;
  76756. (function (TonemappingOperator) {
  76757. /** Hable */
  76758. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76759. /** Reinhard */
  76760. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76761. /** HejiDawson */
  76762. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76763. /** Photographic */
  76764. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76765. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76766. ;
  76767. /**
  76768. * Defines a post process to apply tone mapping
  76769. */
  76770. var TonemapPostProcess = /** @class */ (function (_super) {
  76771. __extends(TonemapPostProcess, _super);
  76772. /**
  76773. * Creates a new TonemapPostProcess
  76774. * @param name defines the name of the postprocess
  76775. * @param _operator defines the operator to use
  76776. * @param exposureAdjustment defines the required exposure adjustement
  76777. * @param camera defines the camera to use (can be null)
  76778. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76779. * @param engine defines the hosting engine (can be ignore if camera is set)
  76780. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76781. */
  76782. function TonemapPostProcess(name, _operator,
  76783. /** Defines the required exposure adjustement */
  76784. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76785. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76786. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76787. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76788. _this._operator = _operator;
  76789. _this.exposureAdjustment = exposureAdjustment;
  76790. var defines = "#define ";
  76791. if (_this._operator === TonemappingOperator.Hable)
  76792. defines += "HABLE_TONEMAPPING";
  76793. else if (_this._operator === TonemappingOperator.Reinhard)
  76794. defines += "REINHARD_TONEMAPPING";
  76795. else if (_this._operator === TonemappingOperator.HejiDawson)
  76796. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76797. else if (_this._operator === TonemappingOperator.Photographic)
  76798. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76799. //sadly a second call to create the effect.
  76800. _this.updateEffect(defines);
  76801. _this.onApply = function (effect) {
  76802. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76803. };
  76804. return _this;
  76805. }
  76806. return TonemapPostProcess;
  76807. }(BABYLON.PostProcess));
  76808. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76809. })(BABYLON || (BABYLON = {}));
  76810. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76811. var BABYLON;
  76812. (function (BABYLON) {
  76813. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76814. __extends(DisplayPassPostProcess, _super);
  76815. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76816. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76817. }
  76818. return DisplayPassPostProcess;
  76819. }(BABYLON.PostProcess));
  76820. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76821. })(BABYLON || (BABYLON = {}));
  76822. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76823. var BABYLON;
  76824. (function (BABYLON) {
  76825. var HighlightsPostProcess = /** @class */ (function (_super) {
  76826. __extends(HighlightsPostProcess, _super);
  76827. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76828. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76829. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76830. }
  76831. return HighlightsPostProcess;
  76832. }(BABYLON.PostProcess));
  76833. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76834. })(BABYLON || (BABYLON = {}));
  76835. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76836. var BABYLON;
  76837. (function (BABYLON) {
  76838. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76839. __extends(ImageProcessingPostProcess, _super);
  76840. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76841. if (camera === void 0) { camera = null; }
  76842. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76843. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76844. _this._fromLinearSpace = true;
  76845. /**
  76846. * Defines cache preventing GC.
  76847. */
  76848. _this._defines = {
  76849. IMAGEPROCESSING: false,
  76850. VIGNETTE: false,
  76851. VIGNETTEBLENDMODEMULTIPLY: false,
  76852. VIGNETTEBLENDMODEOPAQUE: false,
  76853. TONEMAPPING: false,
  76854. CONTRAST: false,
  76855. COLORCURVES: false,
  76856. COLORGRADING: false,
  76857. COLORGRADING3D: false,
  76858. FROMLINEARSPACE: false,
  76859. SAMPLER3DGREENDEPTH: false,
  76860. SAMPLER3DBGRMAP: false,
  76861. IMAGEPROCESSINGPOSTPROCESS: false,
  76862. EXPOSURE: false,
  76863. };
  76864. // Setup the configuration as forced by the constructor. This would then not force the
  76865. // scene materials output in linear space and let untouched the default forward pass.
  76866. if (imageProcessingConfiguration) {
  76867. imageProcessingConfiguration.applyByPostProcess = true;
  76868. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76869. // This will cause the shader to be compiled
  76870. _this.fromLinearSpace = false;
  76871. }
  76872. // Setup the default processing configuration to the scene.
  76873. else {
  76874. _this._attachImageProcessingConfiguration(null, true);
  76875. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76876. }
  76877. _this.onApply = function (effect) {
  76878. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76879. };
  76880. return _this;
  76881. }
  76882. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76883. /**
  76884. * Gets the image processing configuration used either in this material.
  76885. */
  76886. get: function () {
  76887. return this._imageProcessingConfiguration;
  76888. },
  76889. /**
  76890. * Sets the Default image processing configuration used either in the this material.
  76891. *
  76892. * If sets to null, the scene one is in use.
  76893. */
  76894. set: function (value) {
  76895. this._attachImageProcessingConfiguration(value);
  76896. },
  76897. enumerable: true,
  76898. configurable: true
  76899. });
  76900. /**
  76901. * Attaches a new image processing configuration to the PBR Material.
  76902. * @param configuration
  76903. */
  76904. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76905. var _this = this;
  76906. if (doNotBuild === void 0) { doNotBuild = false; }
  76907. if (configuration === this._imageProcessingConfiguration) {
  76908. return;
  76909. }
  76910. // Detaches observer.
  76911. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76912. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76913. }
  76914. // Pick the scene configuration if needed.
  76915. if (!configuration) {
  76916. var scene = null;
  76917. var engine = this.getEngine();
  76918. var camera = this.getCamera();
  76919. if (camera) {
  76920. scene = camera.getScene();
  76921. }
  76922. else if (engine && engine.scenes) {
  76923. var scenes = engine.scenes;
  76924. scene = scenes[scenes.length - 1];
  76925. }
  76926. else {
  76927. scene = BABYLON.Engine.LastCreatedScene;
  76928. }
  76929. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  76930. }
  76931. else {
  76932. this._imageProcessingConfiguration = configuration;
  76933. }
  76934. // Attaches observer.
  76935. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76936. _this._updateParameters();
  76937. });
  76938. // Ensure the effect will be rebuilt.
  76939. if (!doNotBuild) {
  76940. this._updateParameters();
  76941. }
  76942. };
  76943. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  76944. /**
  76945. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76946. */
  76947. get: function () {
  76948. return this.imageProcessingConfiguration.colorCurves;
  76949. },
  76950. /**
  76951. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76952. */
  76953. set: function (value) {
  76954. this.imageProcessingConfiguration.colorCurves = value;
  76955. },
  76956. enumerable: true,
  76957. configurable: true
  76958. });
  76959. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  76960. /**
  76961. * Gets wether the color curves effect is enabled.
  76962. */
  76963. get: function () {
  76964. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76965. },
  76966. /**
  76967. * Sets wether the color curves effect is enabled.
  76968. */
  76969. set: function (value) {
  76970. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76971. },
  76972. enumerable: true,
  76973. configurable: true
  76974. });
  76975. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  76976. /**
  76977. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76978. */
  76979. get: function () {
  76980. return this.imageProcessingConfiguration.colorGradingTexture;
  76981. },
  76982. /**
  76983. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76984. */
  76985. set: function (value) {
  76986. this.imageProcessingConfiguration.colorGradingTexture = value;
  76987. },
  76988. enumerable: true,
  76989. configurable: true
  76990. });
  76991. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  76992. /**
  76993. * Gets wether the color grading effect is enabled.
  76994. */
  76995. get: function () {
  76996. return this.imageProcessingConfiguration.colorGradingEnabled;
  76997. },
  76998. /**
  76999. * Gets wether the color grading effect is enabled.
  77000. */
  77001. set: function (value) {
  77002. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77003. },
  77004. enumerable: true,
  77005. configurable: true
  77006. });
  77007. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77008. /**
  77009. * Gets exposure used in the effect.
  77010. */
  77011. get: function () {
  77012. return this.imageProcessingConfiguration.exposure;
  77013. },
  77014. /**
  77015. * Sets exposure used in the effect.
  77016. */
  77017. set: function (value) {
  77018. this.imageProcessingConfiguration.exposure = value;
  77019. },
  77020. enumerable: true,
  77021. configurable: true
  77022. });
  77023. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77024. /**
  77025. * Gets wether tonemapping is enabled or not.
  77026. */
  77027. get: function () {
  77028. return this._imageProcessingConfiguration.toneMappingEnabled;
  77029. },
  77030. /**
  77031. * Sets wether tonemapping is enabled or not
  77032. */
  77033. set: function (value) {
  77034. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77035. },
  77036. enumerable: true,
  77037. configurable: true
  77038. });
  77039. ;
  77040. ;
  77041. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77042. /**
  77043. * Gets contrast used in the effect.
  77044. */
  77045. get: function () {
  77046. return this.imageProcessingConfiguration.contrast;
  77047. },
  77048. /**
  77049. * Sets contrast used in the effect.
  77050. */
  77051. set: function (value) {
  77052. this.imageProcessingConfiguration.contrast = value;
  77053. },
  77054. enumerable: true,
  77055. configurable: true
  77056. });
  77057. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77058. /**
  77059. * Gets Vignette stretch size.
  77060. */
  77061. get: function () {
  77062. return this.imageProcessingConfiguration.vignetteStretch;
  77063. },
  77064. /**
  77065. * Sets Vignette stretch size.
  77066. */
  77067. set: function (value) {
  77068. this.imageProcessingConfiguration.vignetteStretch = value;
  77069. },
  77070. enumerable: true,
  77071. configurable: true
  77072. });
  77073. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77074. /**
  77075. * Gets Vignette centre X Offset.
  77076. */
  77077. get: function () {
  77078. return this.imageProcessingConfiguration.vignetteCentreX;
  77079. },
  77080. /**
  77081. * Sets Vignette centre X Offset.
  77082. */
  77083. set: function (value) {
  77084. this.imageProcessingConfiguration.vignetteCentreX = value;
  77085. },
  77086. enumerable: true,
  77087. configurable: true
  77088. });
  77089. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77090. /**
  77091. * Gets Vignette centre Y Offset.
  77092. */
  77093. get: function () {
  77094. return this.imageProcessingConfiguration.vignetteCentreY;
  77095. },
  77096. /**
  77097. * Sets Vignette centre Y Offset.
  77098. */
  77099. set: function (value) {
  77100. this.imageProcessingConfiguration.vignetteCentreY = value;
  77101. },
  77102. enumerable: true,
  77103. configurable: true
  77104. });
  77105. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77106. /**
  77107. * Gets Vignette weight or intensity of the vignette effect.
  77108. */
  77109. get: function () {
  77110. return this.imageProcessingConfiguration.vignetteWeight;
  77111. },
  77112. /**
  77113. * Sets Vignette weight or intensity of the vignette effect.
  77114. */
  77115. set: function (value) {
  77116. this.imageProcessingConfiguration.vignetteWeight = value;
  77117. },
  77118. enumerable: true,
  77119. configurable: true
  77120. });
  77121. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77122. /**
  77123. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77124. * if vignetteEnabled is set to true.
  77125. */
  77126. get: function () {
  77127. return this.imageProcessingConfiguration.vignetteColor;
  77128. },
  77129. /**
  77130. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77131. * if vignetteEnabled is set to true.
  77132. */
  77133. set: function (value) {
  77134. this.imageProcessingConfiguration.vignetteColor = value;
  77135. },
  77136. enumerable: true,
  77137. configurable: true
  77138. });
  77139. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77140. /**
  77141. * Gets Camera field of view used by the Vignette effect.
  77142. */
  77143. get: function () {
  77144. return this.imageProcessingConfiguration.vignetteCameraFov;
  77145. },
  77146. /**
  77147. * Sets Camera field of view used by the Vignette effect.
  77148. */
  77149. set: function (value) {
  77150. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77151. },
  77152. enumerable: true,
  77153. configurable: true
  77154. });
  77155. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77156. /**
  77157. * Gets the vignette blend mode allowing different kind of effect.
  77158. */
  77159. get: function () {
  77160. return this.imageProcessingConfiguration.vignetteBlendMode;
  77161. },
  77162. /**
  77163. * Sets the vignette blend mode allowing different kind of effect.
  77164. */
  77165. set: function (value) {
  77166. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77167. },
  77168. enumerable: true,
  77169. configurable: true
  77170. });
  77171. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77172. /**
  77173. * Gets wether the vignette effect is enabled.
  77174. */
  77175. get: function () {
  77176. return this.imageProcessingConfiguration.vignetteEnabled;
  77177. },
  77178. /**
  77179. * Sets wether the vignette effect is enabled.
  77180. */
  77181. set: function (value) {
  77182. this.imageProcessingConfiguration.vignetteEnabled = value;
  77183. },
  77184. enumerable: true,
  77185. configurable: true
  77186. });
  77187. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77188. /**
  77189. * Gets wether the input of the processing is in Gamma or Linear Space.
  77190. */
  77191. get: function () {
  77192. return this._fromLinearSpace;
  77193. },
  77194. /**
  77195. * Sets wether the input of the processing is in Gamma or Linear Space.
  77196. */
  77197. set: function (value) {
  77198. if (this._fromLinearSpace === value) {
  77199. return;
  77200. }
  77201. this._fromLinearSpace = value;
  77202. this._updateParameters();
  77203. },
  77204. enumerable: true,
  77205. configurable: true
  77206. });
  77207. ImageProcessingPostProcess.prototype.getClassName = function () {
  77208. return "ImageProcessingPostProcess";
  77209. };
  77210. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77211. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77212. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77213. var defines = "";
  77214. for (var define in this._defines) {
  77215. if (this._defines[define]) {
  77216. defines += "#define " + define + ";\r\n";
  77217. }
  77218. }
  77219. var samplers = ["textureSampler"];
  77220. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77221. var uniforms = ["scale"];
  77222. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77223. this.updateEffect(defines, uniforms, samplers);
  77224. };
  77225. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77226. _super.prototype.dispose.call(this, camera);
  77227. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77228. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77229. }
  77230. this.imageProcessingConfiguration.applyByPostProcess = false;
  77231. };
  77232. __decorate([
  77233. BABYLON.serialize()
  77234. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77235. return ImageProcessingPostProcess;
  77236. }(BABYLON.PostProcess));
  77237. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77238. })(BABYLON || (BABYLON = {}));
  77239. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77240. var BABYLON;
  77241. (function (BABYLON) {
  77242. /**
  77243. * Class used to store bone information
  77244. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77245. */
  77246. var Bone = /** @class */ (function (_super) {
  77247. __extends(Bone, _super);
  77248. /**
  77249. * Create a new bone
  77250. * @param name defines the bone name
  77251. * @param skeleton defines the parent skeleton
  77252. * @param parentBone defines the parent (can be null if the bone is the root)
  77253. * @param localMatrix defines the local matrix
  77254. * @param restPose defines the rest pose matrix
  77255. * @param baseMatrix defines the base matrix
  77256. * @param index defines index of the bone in the hiearchy
  77257. */
  77258. function Bone(
  77259. /**
  77260. * defines the bone name
  77261. */
  77262. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77263. if (parentBone === void 0) { parentBone = null; }
  77264. if (localMatrix === void 0) { localMatrix = null; }
  77265. if (restPose === void 0) { restPose = null; }
  77266. if (baseMatrix === void 0) { baseMatrix = null; }
  77267. if (index === void 0) { index = null; }
  77268. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77269. _this.name = name;
  77270. /**
  77271. * Gets the list of child bones
  77272. */
  77273. _this.children = new Array();
  77274. /** Gets the animations associated with this bone */
  77275. _this.animations = new Array();
  77276. /**
  77277. * @hidden Internal only
  77278. * Set this value to map this bone to a different index in the transform matrices
  77279. * Set this value to -1 to exclude the bone from the transform matrices
  77280. */
  77281. _this._index = null;
  77282. _this._absoluteTransform = new BABYLON.Matrix();
  77283. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77284. _this._scalingDeterminant = 1;
  77285. _this._worldTransform = new BABYLON.Matrix();
  77286. _this._needToDecompose = true;
  77287. _this._needToCompose = false;
  77288. _this._skeleton = skeleton;
  77289. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77290. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77291. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77292. _this._index = index;
  77293. skeleton.bones.push(_this);
  77294. _this.setParent(parentBone, false);
  77295. if (baseMatrix || localMatrix) {
  77296. _this._updateDifferenceMatrix();
  77297. }
  77298. return _this;
  77299. }
  77300. Object.defineProperty(Bone.prototype, "_matrix", {
  77301. /** @hidden */
  77302. get: function () {
  77303. this._compose();
  77304. return this._localMatrix;
  77305. },
  77306. /** @hidden */
  77307. set: function (value) {
  77308. this._localMatrix.copyFrom(value);
  77309. this._needToDecompose = true;
  77310. },
  77311. enumerable: true,
  77312. configurable: true
  77313. });
  77314. // Members
  77315. /**
  77316. * Gets the parent skeleton
  77317. * @returns a skeleton
  77318. */
  77319. Bone.prototype.getSkeleton = function () {
  77320. return this._skeleton;
  77321. };
  77322. /**
  77323. * Gets parent bone
  77324. * @returns a bone or null if the bone is the root of the bone hierarchy
  77325. */
  77326. Bone.prototype.getParent = function () {
  77327. return this._parent;
  77328. };
  77329. /**
  77330. * Sets the parent bone
  77331. * @param parent defines the parent (can be null if the bone is the root)
  77332. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77333. */
  77334. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77335. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77336. if (this._parent === parent) {
  77337. return;
  77338. }
  77339. if (this._parent) {
  77340. var index = this._parent.children.indexOf(this);
  77341. if (index !== -1) {
  77342. this._parent.children.splice(index, 1);
  77343. }
  77344. }
  77345. this._parent = parent;
  77346. if (this._parent) {
  77347. this._parent.children.push(this);
  77348. }
  77349. if (updateDifferenceMatrix) {
  77350. this._updateDifferenceMatrix();
  77351. }
  77352. this.markAsDirty();
  77353. };
  77354. /**
  77355. * Gets the local matrix
  77356. * @returns a matrix
  77357. */
  77358. Bone.prototype.getLocalMatrix = function () {
  77359. this._compose();
  77360. return this._localMatrix;
  77361. };
  77362. /**
  77363. * Gets the base matrix (initial matrix which remains unchanged)
  77364. * @returns a matrix
  77365. */
  77366. Bone.prototype.getBaseMatrix = function () {
  77367. return this._baseMatrix;
  77368. };
  77369. /**
  77370. * Gets the rest pose matrix
  77371. * @returns a matrix
  77372. */
  77373. Bone.prototype.getRestPose = function () {
  77374. return this._restPose;
  77375. };
  77376. /**
  77377. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77378. */
  77379. Bone.prototype.getWorldMatrix = function () {
  77380. return this._worldTransform;
  77381. };
  77382. /**
  77383. * Sets the local matrix to rest pose matrix
  77384. */
  77385. Bone.prototype.returnToRest = function () {
  77386. this.updateMatrix(this._restPose.clone());
  77387. };
  77388. /**
  77389. * Gets the inverse of the absolute transform matrix.
  77390. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77391. * @returns a matrix
  77392. */
  77393. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77394. return this._invertedAbsoluteTransform;
  77395. };
  77396. /**
  77397. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77398. * @returns a matrix
  77399. */
  77400. Bone.prototype.getAbsoluteTransform = function () {
  77401. return this._absoluteTransform;
  77402. };
  77403. Object.defineProperty(Bone.prototype, "position", {
  77404. // Properties (matches AbstractMesh properties)
  77405. /** Gets or sets current position (in local space) */
  77406. get: function () {
  77407. this._decompose();
  77408. return this._localPosition;
  77409. },
  77410. set: function (newPosition) {
  77411. this._decompose();
  77412. this._localPosition.copyFrom(newPosition);
  77413. this._markAsDirtyAndCompose();
  77414. },
  77415. enumerable: true,
  77416. configurable: true
  77417. });
  77418. Object.defineProperty(Bone.prototype, "rotation", {
  77419. /** Gets or sets current rotation (in local space) */
  77420. get: function () {
  77421. return this.getRotation();
  77422. },
  77423. set: function (newRotation) {
  77424. this.setRotation(newRotation);
  77425. },
  77426. enumerable: true,
  77427. configurable: true
  77428. });
  77429. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77430. /** Gets or sets current rotation quaternion (in local space) */
  77431. get: function () {
  77432. this._decompose();
  77433. return this._localRotation;
  77434. },
  77435. set: function (newRotation) {
  77436. this.setRotationQuaternion(newRotation);
  77437. },
  77438. enumerable: true,
  77439. configurable: true
  77440. });
  77441. Object.defineProperty(Bone.prototype, "scaling", {
  77442. /** Gets or sets current scaling (in local space) */
  77443. get: function () {
  77444. return this.getScale();
  77445. },
  77446. set: function (newScaling) {
  77447. this.setScale(newScaling);
  77448. },
  77449. enumerable: true,
  77450. configurable: true
  77451. });
  77452. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77453. /**
  77454. * Gets the animation properties override
  77455. */
  77456. get: function () {
  77457. return this._skeleton.animationPropertiesOverride;
  77458. },
  77459. enumerable: true,
  77460. configurable: true
  77461. });
  77462. // Methods
  77463. Bone.prototype._decompose = function () {
  77464. if (!this._needToDecompose) {
  77465. return;
  77466. }
  77467. this._needToDecompose = false;
  77468. if (!this._localScaling) {
  77469. this._localScaling = BABYLON.Vector3.Zero();
  77470. this._localRotation = BABYLON.Quaternion.Zero();
  77471. this._localPosition = BABYLON.Vector3.Zero();
  77472. }
  77473. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77474. };
  77475. Bone.prototype._compose = function () {
  77476. if (!this._needToCompose) {
  77477. return;
  77478. }
  77479. this._needToCompose = false;
  77480. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77481. };
  77482. /**
  77483. * Update the base and local matrices
  77484. * @param matrix defines the new base or local matrix
  77485. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77486. * @param updateLocalMatrix defines if the local matrix should be updated
  77487. */
  77488. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77489. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77490. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77491. this._baseMatrix.copyFrom(matrix);
  77492. if (updateDifferenceMatrix) {
  77493. this._updateDifferenceMatrix();
  77494. }
  77495. if (updateLocalMatrix) {
  77496. this._localMatrix.copyFrom(matrix);
  77497. this._markAsDirtyAndDecompose();
  77498. }
  77499. else {
  77500. this.markAsDirty();
  77501. }
  77502. };
  77503. /** @hidden */
  77504. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77505. if (updateChildren === void 0) { updateChildren = true; }
  77506. if (!rootMatrix) {
  77507. rootMatrix = this._baseMatrix;
  77508. }
  77509. if (this._parent) {
  77510. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77511. }
  77512. else {
  77513. this._absoluteTransform.copyFrom(rootMatrix);
  77514. }
  77515. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77516. if (updateChildren) {
  77517. for (var index = 0; index < this.children.length; index++) {
  77518. this.children[index]._updateDifferenceMatrix();
  77519. }
  77520. }
  77521. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77522. };
  77523. /**
  77524. * Flag the bone as dirty (Forcing it to update everything)
  77525. */
  77526. Bone.prototype.markAsDirty = function () {
  77527. this._currentRenderId++;
  77528. this._childRenderId++;
  77529. this._skeleton._markAsDirty();
  77530. };
  77531. Bone.prototype._markAsDirtyAndCompose = function () {
  77532. this.markAsDirty();
  77533. this._needToCompose = true;
  77534. };
  77535. Bone.prototype._markAsDirtyAndDecompose = function () {
  77536. this.markAsDirty();
  77537. this._needToDecompose = true;
  77538. };
  77539. /**
  77540. * Copy an animation range from another bone
  77541. * @param source defines the source bone
  77542. * @param rangeName defines the range name to copy
  77543. * @param frameOffset defines the frame offset
  77544. * @param rescaleAsRequired defines if rescaling must be applied if required
  77545. * @param skelDimensionsRatio defines the scaling ratio
  77546. * @returns true if operation was successful
  77547. */
  77548. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77549. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77550. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77551. // all animation may be coming from a library skeleton, so may need to create animation
  77552. if (this.animations.length === 0) {
  77553. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77554. this.animations[0].setKeys([]);
  77555. }
  77556. // get animation info / verify there is such a range from the source bone
  77557. var sourceRange = source.animations[0].getRange(rangeName);
  77558. if (!sourceRange) {
  77559. return false;
  77560. }
  77561. var from = sourceRange.from;
  77562. var to = sourceRange.to;
  77563. var sourceKeys = source.animations[0].getKeys();
  77564. // rescaling prep
  77565. var sourceBoneLength = source.length;
  77566. var sourceParent = source.getParent();
  77567. var parent = this.getParent();
  77568. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77569. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77570. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77571. var destKeys = this.animations[0].getKeys();
  77572. // loop vars declaration
  77573. var orig;
  77574. var origTranslation;
  77575. var mat;
  77576. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77577. orig = sourceKeys[key];
  77578. if (orig.frame >= from && orig.frame <= to) {
  77579. if (rescaleAsRequired) {
  77580. mat = orig.value.clone();
  77581. // scale based on parent ratio, when bone has parent
  77582. if (parentScalingReqd) {
  77583. origTranslation = mat.getTranslation();
  77584. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77585. // scale based on skeleton dimension ratio when root bone, and value is passed
  77586. }
  77587. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77588. origTranslation = mat.getTranslation();
  77589. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77590. // use original when root bone, and no data for skelDimensionsRatio
  77591. }
  77592. else {
  77593. mat = orig.value;
  77594. }
  77595. }
  77596. else {
  77597. mat = orig.value;
  77598. }
  77599. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77600. }
  77601. }
  77602. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77603. return true;
  77604. };
  77605. /**
  77606. * Translate the bone in local or world space
  77607. * @param vec The amount to translate the bone
  77608. * @param space The space that the translation is in
  77609. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77610. */
  77611. Bone.prototype.translate = function (vec, space, mesh) {
  77612. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77613. var lm = this.getLocalMatrix();
  77614. if (space == BABYLON.Space.LOCAL) {
  77615. lm.m[12] += vec.x;
  77616. lm.m[13] += vec.y;
  77617. lm.m[14] += vec.z;
  77618. }
  77619. else {
  77620. var wm = null;
  77621. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77622. if (mesh) {
  77623. wm = mesh.getWorldMatrix();
  77624. }
  77625. this._skeleton.computeAbsoluteTransforms();
  77626. var tmat = Bone._tmpMats[0];
  77627. var tvec = Bone._tmpVecs[0];
  77628. if (this._parent) {
  77629. if (mesh && wm) {
  77630. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77631. tmat.multiplyToRef(wm, tmat);
  77632. }
  77633. else {
  77634. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77635. }
  77636. }
  77637. tmat.m[12] = 0;
  77638. tmat.m[13] = 0;
  77639. tmat.m[14] = 0;
  77640. tmat.invert();
  77641. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77642. lm.m[12] += tvec.x;
  77643. lm.m[13] += tvec.y;
  77644. lm.m[14] += tvec.z;
  77645. }
  77646. this._markAsDirtyAndDecompose();
  77647. };
  77648. /**
  77649. * Set the postion of the bone in local or world space
  77650. * @param position The position to set the bone
  77651. * @param space The space that the position is in
  77652. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77653. */
  77654. Bone.prototype.setPosition = function (position, space, mesh) {
  77655. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77656. var lm = this.getLocalMatrix();
  77657. if (space == BABYLON.Space.LOCAL) {
  77658. lm.m[12] = position.x;
  77659. lm.m[13] = position.y;
  77660. lm.m[14] = position.z;
  77661. }
  77662. else {
  77663. var wm = null;
  77664. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77665. if (mesh) {
  77666. wm = mesh.getWorldMatrix();
  77667. }
  77668. this._skeleton.computeAbsoluteTransforms();
  77669. var tmat = Bone._tmpMats[0];
  77670. var vec = Bone._tmpVecs[0];
  77671. if (this._parent) {
  77672. if (mesh && wm) {
  77673. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77674. tmat.multiplyToRef(wm, tmat);
  77675. }
  77676. else {
  77677. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77678. }
  77679. }
  77680. tmat.invert();
  77681. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77682. lm.m[12] = vec.x;
  77683. lm.m[13] = vec.y;
  77684. lm.m[14] = vec.z;
  77685. }
  77686. this._markAsDirtyAndDecompose();
  77687. };
  77688. /**
  77689. * Set the absolute position of the bone (world space)
  77690. * @param position The position to set the bone
  77691. * @param mesh The mesh that this bone is attached to
  77692. */
  77693. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77694. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77695. };
  77696. /**
  77697. * Scale the bone on the x, y and z axes (in local space)
  77698. * @param x The amount to scale the bone on the x axis
  77699. * @param y The amount to scale the bone on the y axis
  77700. * @param z The amount to scale the bone on the z axis
  77701. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77702. */
  77703. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77704. if (scaleChildren === void 0) { scaleChildren = false; }
  77705. var locMat = this.getLocalMatrix();
  77706. // Apply new scaling on top of current local matrix
  77707. var scaleMat = Bone._tmpMats[0];
  77708. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77709. scaleMat.multiplyToRef(locMat, locMat);
  77710. // Invert scaling matrix and apply the inverse to all children
  77711. scaleMat.invert();
  77712. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77713. var child = _a[_i];
  77714. var cm = child.getLocalMatrix();
  77715. cm.multiplyToRef(scaleMat, cm);
  77716. cm.m[12] *= x;
  77717. cm.m[13] *= y;
  77718. cm.m[14] *= z;
  77719. child._markAsDirtyAndDecompose();
  77720. }
  77721. this._markAsDirtyAndDecompose();
  77722. if (scaleChildren) {
  77723. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77724. var child = _c[_b];
  77725. child.scale(x, y, z, scaleChildren);
  77726. }
  77727. }
  77728. };
  77729. /**
  77730. * Set the bone scaling in local space
  77731. * @param scale defines the scaling vector
  77732. */
  77733. Bone.prototype.setScale = function (scale) {
  77734. this._decompose();
  77735. this._localScaling.copyFrom(scale);
  77736. this._markAsDirtyAndCompose();
  77737. };
  77738. /**
  77739. * Gets the current scaling in local space
  77740. * @returns the current scaling vector
  77741. */
  77742. Bone.prototype.getScale = function () {
  77743. this._decompose();
  77744. return this._localScaling;
  77745. };
  77746. /**
  77747. * Gets the current scaling in local space and stores it in a target vector
  77748. * @param result defines the target vector
  77749. */
  77750. Bone.prototype.getScaleToRef = function (result) {
  77751. this._decompose();
  77752. result.copyFrom(this._localScaling);
  77753. };
  77754. /**
  77755. * Set the yaw, pitch, and roll of the bone in local or world space
  77756. * @param yaw The rotation of the bone on the y axis
  77757. * @param pitch The rotation of the bone on the x axis
  77758. * @param roll The rotation of the bone on the z axis
  77759. * @param space The space that the axes of rotation are in
  77760. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77761. */
  77762. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77763. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77764. if (space === BABYLON.Space.LOCAL) {
  77765. var quat = Bone._tmpQuat;
  77766. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77767. this.setRotationQuaternion(quat, space, mesh);
  77768. return;
  77769. }
  77770. var rotMatInv = Bone._tmpMats[0];
  77771. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77772. return;
  77773. }
  77774. var rotMat = Bone._tmpMats[1];
  77775. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77776. rotMatInv.multiplyToRef(rotMat, rotMat);
  77777. this._rotateWithMatrix(rotMat, space, mesh);
  77778. };
  77779. /**
  77780. * Add a rotation to the bone on an axis in local or world space
  77781. * @param axis The axis to rotate the bone on
  77782. * @param amount The amount to rotate the bone
  77783. * @param space The space that the axis is in
  77784. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77785. */
  77786. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77787. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77788. var rmat = Bone._tmpMats[0];
  77789. rmat.m[12] = 0;
  77790. rmat.m[13] = 0;
  77791. rmat.m[14] = 0;
  77792. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77793. this._rotateWithMatrix(rmat, space, mesh);
  77794. };
  77795. /**
  77796. * Set the rotation of the bone to a particular axis angle in local or world space
  77797. * @param axis The axis to rotate the bone on
  77798. * @param angle The angle that the bone should be rotated to
  77799. * @param space The space that the axis is in
  77800. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77801. */
  77802. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77803. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77804. if (space === BABYLON.Space.LOCAL) {
  77805. var quat = Bone._tmpQuat;
  77806. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77807. this.setRotationQuaternion(quat, space, mesh);
  77808. return;
  77809. }
  77810. var rotMatInv = Bone._tmpMats[0];
  77811. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77812. return;
  77813. }
  77814. var rotMat = Bone._tmpMats[1];
  77815. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77816. rotMatInv.multiplyToRef(rotMat, rotMat);
  77817. this._rotateWithMatrix(rotMat, space, mesh);
  77818. };
  77819. /**
  77820. * Set the euler rotation of the bone in local of world space
  77821. * @param rotation The euler rotation that the bone should be set to
  77822. * @param space The space that the rotation is in
  77823. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77824. */
  77825. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77826. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77827. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77828. };
  77829. /**
  77830. * Set the quaternion rotation of the bone in local of world space
  77831. * @param quat The quaternion rotation that the bone should be set to
  77832. * @param space The space that the rotation is in
  77833. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77834. */
  77835. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77836. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77837. if (space === BABYLON.Space.LOCAL) {
  77838. this._decompose();
  77839. this._localRotation.copyFrom(quat);
  77840. this._markAsDirtyAndCompose();
  77841. return;
  77842. }
  77843. var rotMatInv = Bone._tmpMats[0];
  77844. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77845. return;
  77846. }
  77847. var rotMat = Bone._tmpMats[1];
  77848. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77849. rotMatInv.multiplyToRef(rotMat, rotMat);
  77850. this._rotateWithMatrix(rotMat, space, mesh);
  77851. };
  77852. /**
  77853. * Set the rotation matrix of the bone in local of world space
  77854. * @param rotMat The rotation matrix that the bone should be set to
  77855. * @param space The space that the rotation is in
  77856. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77857. */
  77858. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77859. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77860. if (space === BABYLON.Space.LOCAL) {
  77861. var quat = Bone._tmpQuat;
  77862. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77863. this.setRotationQuaternion(quat, space, mesh);
  77864. return;
  77865. }
  77866. var rotMatInv = Bone._tmpMats[0];
  77867. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77868. return;
  77869. }
  77870. var rotMat2 = Bone._tmpMats[1];
  77871. rotMat2.copyFrom(rotMat);
  77872. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77873. this._rotateWithMatrix(rotMat2, space, mesh);
  77874. };
  77875. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77876. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77877. var lmat = this.getLocalMatrix();
  77878. var lx = lmat.m[12];
  77879. var ly = lmat.m[13];
  77880. var lz = lmat.m[14];
  77881. var parent = this.getParent();
  77882. var parentScale = Bone._tmpMats[3];
  77883. var parentScaleInv = Bone._tmpMats[4];
  77884. if (parent && space == BABYLON.Space.WORLD) {
  77885. if (mesh) {
  77886. parentScale.copyFrom(mesh.getWorldMatrix());
  77887. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77888. }
  77889. else {
  77890. parentScale.copyFrom(parent.getAbsoluteTransform());
  77891. }
  77892. parentScaleInv.copyFrom(parentScale);
  77893. parentScaleInv.invert();
  77894. lmat.multiplyToRef(parentScale, lmat);
  77895. lmat.multiplyToRef(rmat, lmat);
  77896. lmat.multiplyToRef(parentScaleInv, lmat);
  77897. }
  77898. else {
  77899. if (space == BABYLON.Space.WORLD && mesh) {
  77900. parentScale.copyFrom(mesh.getWorldMatrix());
  77901. parentScaleInv.copyFrom(parentScale);
  77902. parentScaleInv.invert();
  77903. lmat.multiplyToRef(parentScale, lmat);
  77904. lmat.multiplyToRef(rmat, lmat);
  77905. lmat.multiplyToRef(parentScaleInv, lmat);
  77906. }
  77907. else {
  77908. lmat.multiplyToRef(rmat, lmat);
  77909. }
  77910. }
  77911. lmat.m[12] = lx;
  77912. lmat.m[13] = ly;
  77913. lmat.m[14] = lz;
  77914. this.computeAbsoluteTransforms();
  77915. this._markAsDirtyAndDecompose();
  77916. };
  77917. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77918. var scaleMatrix = Bone._tmpMats[2];
  77919. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77920. if (mesh) {
  77921. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77922. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77923. }
  77924. rotMatInv.invert();
  77925. if (isNaN(rotMatInv.m[0])) {
  77926. // Matrix failed to invert.
  77927. // This can happen if scale is zero for example.
  77928. return false;
  77929. }
  77930. scaleMatrix.m[0] *= this._scalingDeterminant;
  77931. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  77932. return true;
  77933. };
  77934. /**
  77935. * Get the position of the bone in local or world space
  77936. * @param space The space that the returned position is in
  77937. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77938. * @returns The position of the bone
  77939. */
  77940. Bone.prototype.getPosition = function (space, mesh) {
  77941. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77942. if (mesh === void 0) { mesh = null; }
  77943. var pos = BABYLON.Vector3.Zero();
  77944. this.getPositionToRef(space, mesh, pos);
  77945. return pos;
  77946. };
  77947. /**
  77948. * Copy the position of the bone to a vector3 in local or world space
  77949. * @param space The space that the returned position is in
  77950. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77951. * @param result The vector3 to copy the position to
  77952. */
  77953. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  77954. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77955. if (space == BABYLON.Space.LOCAL) {
  77956. var lm = this.getLocalMatrix();
  77957. result.x = lm.m[12];
  77958. result.y = lm.m[13];
  77959. result.z = lm.m[14];
  77960. }
  77961. else {
  77962. var wm = null;
  77963. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77964. if (mesh) {
  77965. wm = mesh.getWorldMatrix();
  77966. }
  77967. this._skeleton.computeAbsoluteTransforms();
  77968. var tmat = Bone._tmpMats[0];
  77969. if (mesh && wm) {
  77970. tmat.copyFrom(this.getAbsoluteTransform());
  77971. tmat.multiplyToRef(wm, tmat);
  77972. }
  77973. else {
  77974. tmat = this.getAbsoluteTransform();
  77975. }
  77976. result.x = tmat.m[12];
  77977. result.y = tmat.m[13];
  77978. result.z = tmat.m[14];
  77979. }
  77980. };
  77981. /**
  77982. * Get the absolute position of the bone (world space)
  77983. * @param mesh The mesh that this bone is attached to
  77984. * @returns The absolute position of the bone
  77985. */
  77986. Bone.prototype.getAbsolutePosition = function (mesh) {
  77987. if (mesh === void 0) { mesh = null; }
  77988. var pos = BABYLON.Vector3.Zero();
  77989. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  77990. return pos;
  77991. };
  77992. /**
  77993. * Copy the absolute position of the bone (world space) to the result param
  77994. * @param mesh The mesh that this bone is attached to
  77995. * @param result The vector3 to copy the absolute position to
  77996. */
  77997. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  77998. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  77999. };
  78000. /**
  78001. * Compute the absolute transforms of this bone and its children
  78002. */
  78003. Bone.prototype.computeAbsoluteTransforms = function () {
  78004. this._compose();
  78005. if (this._parent) {
  78006. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78007. }
  78008. else {
  78009. this._absoluteTransform.copyFrom(this._localMatrix);
  78010. var poseMatrix = this._skeleton.getPoseMatrix();
  78011. if (poseMatrix) {
  78012. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78013. }
  78014. }
  78015. var children = this.children;
  78016. var len = children.length;
  78017. for (var i = 0; i < len; i++) {
  78018. children[i].computeAbsoluteTransforms();
  78019. }
  78020. };
  78021. /**
  78022. * Get the world direction from an axis that is in the local space of the bone
  78023. * @param localAxis The local direction that is used to compute the world direction
  78024. * @param mesh The mesh that this bone is attached to
  78025. * @returns The world direction
  78026. */
  78027. Bone.prototype.getDirection = function (localAxis, mesh) {
  78028. if (mesh === void 0) { mesh = null; }
  78029. var result = BABYLON.Vector3.Zero();
  78030. this.getDirectionToRef(localAxis, mesh, result);
  78031. return result;
  78032. };
  78033. /**
  78034. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78035. * @param localAxis The local direction that is used to compute the world direction
  78036. * @param mesh The mesh that this bone is attached to
  78037. * @param result The vector3 that the world direction will be copied to
  78038. */
  78039. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78040. if (mesh === void 0) { mesh = null; }
  78041. var wm = null;
  78042. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78043. if (mesh) {
  78044. wm = mesh.getWorldMatrix();
  78045. }
  78046. this._skeleton.computeAbsoluteTransforms();
  78047. var mat = Bone._tmpMats[0];
  78048. mat.copyFrom(this.getAbsoluteTransform());
  78049. if (mesh && wm) {
  78050. mat.multiplyToRef(wm, mat);
  78051. }
  78052. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78053. result.normalize();
  78054. };
  78055. /**
  78056. * Get the euler rotation of the bone in local or world space
  78057. * @param space The space that the rotation should be in
  78058. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78059. * @returns The euler rotation
  78060. */
  78061. Bone.prototype.getRotation = function (space, mesh) {
  78062. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78063. if (mesh === void 0) { mesh = null; }
  78064. var result = BABYLON.Vector3.Zero();
  78065. this.getRotationToRef(space, mesh, result);
  78066. return result;
  78067. };
  78068. /**
  78069. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78070. * @param space The space that the rotation should be in
  78071. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78072. * @param result The vector3 that the rotation should be copied to
  78073. */
  78074. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78075. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78076. if (mesh === void 0) { mesh = null; }
  78077. var quat = Bone._tmpQuat;
  78078. this.getRotationQuaternionToRef(space, mesh, quat);
  78079. quat.toEulerAnglesToRef(result);
  78080. };
  78081. /**
  78082. * Get the quaternion rotation of the bone in either local or world space
  78083. * @param space The space that the rotation should be in
  78084. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78085. * @returns The quaternion rotation
  78086. */
  78087. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78088. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78089. if (mesh === void 0) { mesh = null; }
  78090. var result = BABYLON.Quaternion.Identity();
  78091. this.getRotationQuaternionToRef(space, mesh, result);
  78092. return result;
  78093. };
  78094. /**
  78095. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78096. * @param space The space that the rotation should be in
  78097. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78098. * @param result The quaternion that the rotation should be copied to
  78099. */
  78100. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78101. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78102. if (mesh === void 0) { mesh = null; }
  78103. if (space == BABYLON.Space.LOCAL) {
  78104. this._decompose();
  78105. result.copyFrom(this._localRotation);
  78106. }
  78107. else {
  78108. var mat = Bone._tmpMats[0];
  78109. var amat = this.getAbsoluteTransform();
  78110. if (mesh) {
  78111. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78112. }
  78113. else {
  78114. mat.copyFrom(amat);
  78115. }
  78116. mat.m[0] *= this._scalingDeterminant;
  78117. mat.m[1] *= this._scalingDeterminant;
  78118. mat.m[2] *= this._scalingDeterminant;
  78119. mat.decompose(undefined, result, undefined);
  78120. }
  78121. };
  78122. /**
  78123. * Get the rotation matrix of the bone in local or world space
  78124. * @param space The space that the rotation should be in
  78125. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78126. * @returns The rotation matrix
  78127. */
  78128. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78129. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78130. var result = BABYLON.Matrix.Identity();
  78131. this.getRotationMatrixToRef(space, mesh, result);
  78132. return result;
  78133. };
  78134. /**
  78135. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78136. * @param space The space that the rotation should be in
  78137. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78138. * @param result The quaternion that the rotation should be copied to
  78139. */
  78140. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78141. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78142. if (space == BABYLON.Space.LOCAL) {
  78143. this.getLocalMatrix().getRotationMatrixToRef(result);
  78144. }
  78145. else {
  78146. var mat = Bone._tmpMats[0];
  78147. var amat = this.getAbsoluteTransform();
  78148. if (mesh) {
  78149. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78150. }
  78151. else {
  78152. mat.copyFrom(amat);
  78153. }
  78154. mat.m[0] *= this._scalingDeterminant;
  78155. mat.m[1] *= this._scalingDeterminant;
  78156. mat.m[2] *= this._scalingDeterminant;
  78157. mat.getRotationMatrixToRef(result);
  78158. }
  78159. };
  78160. /**
  78161. * Get the world position of a point that is in the local space of the bone
  78162. * @param position The local position
  78163. * @param mesh The mesh that this bone is attached to
  78164. * @returns The world position
  78165. */
  78166. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78167. if (mesh === void 0) { mesh = null; }
  78168. var result = BABYLON.Vector3.Zero();
  78169. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78170. return result;
  78171. };
  78172. /**
  78173. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78174. * @param position The local position
  78175. * @param mesh The mesh that this bone is attached to
  78176. * @param result The vector3 that the world position should be copied to
  78177. */
  78178. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78179. if (mesh === void 0) { mesh = null; }
  78180. var wm = null;
  78181. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78182. if (mesh) {
  78183. wm = mesh.getWorldMatrix();
  78184. }
  78185. this._skeleton.computeAbsoluteTransforms();
  78186. var tmat = Bone._tmpMats[0];
  78187. if (mesh && wm) {
  78188. tmat.copyFrom(this.getAbsoluteTransform());
  78189. tmat.multiplyToRef(wm, tmat);
  78190. }
  78191. else {
  78192. tmat = this.getAbsoluteTransform();
  78193. }
  78194. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78195. };
  78196. /**
  78197. * Get the local position of a point that is in world space
  78198. * @param position The world position
  78199. * @param mesh The mesh that this bone is attached to
  78200. * @returns The local position
  78201. */
  78202. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78203. if (mesh === void 0) { mesh = null; }
  78204. var result = BABYLON.Vector3.Zero();
  78205. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78206. return result;
  78207. };
  78208. /**
  78209. * Get the local position of a point that is in world space and copy it to the result param
  78210. * @param position The world position
  78211. * @param mesh The mesh that this bone is attached to
  78212. * @param result The vector3 that the local position should be copied to
  78213. */
  78214. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78215. if (mesh === void 0) { mesh = null; }
  78216. var wm = null;
  78217. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78218. if (mesh) {
  78219. wm = mesh.getWorldMatrix();
  78220. }
  78221. this._skeleton.computeAbsoluteTransforms();
  78222. var tmat = Bone._tmpMats[0];
  78223. tmat.copyFrom(this.getAbsoluteTransform());
  78224. if (mesh && wm) {
  78225. tmat.multiplyToRef(wm, tmat);
  78226. }
  78227. tmat.invert();
  78228. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78229. };
  78230. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78231. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78232. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78233. return Bone;
  78234. }(BABYLON.Node));
  78235. BABYLON.Bone = Bone;
  78236. })(BABYLON || (BABYLON = {}));
  78237. //# sourceMappingURL=babylon.bone.js.map
  78238. var BABYLON;
  78239. (function (BABYLON) {
  78240. /**
  78241. * Class used to apply inverse kinematics to bones
  78242. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78243. */
  78244. var BoneIKController = /** @class */ (function () {
  78245. /**
  78246. * Creates a new BoneIKController
  78247. * @param mesh defines the mesh to control
  78248. * @param bone defines the bone to control
  78249. * @param options defines options to set up the controller
  78250. */
  78251. function BoneIKController(mesh, bone, options) {
  78252. /**
  78253. * Gets or sets the target position
  78254. */
  78255. this.targetPosition = BABYLON.Vector3.Zero();
  78256. /**
  78257. * Gets or sets the pole target position
  78258. */
  78259. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78260. /**
  78261. * Gets or sets the pole target local offset
  78262. */
  78263. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78264. /**
  78265. * Gets or sets the pole angle
  78266. */
  78267. this.poleAngle = 0;
  78268. /**
  78269. * 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)
  78270. */
  78271. this.slerpAmount = 1;
  78272. this._bone1Quat = BABYLON.Quaternion.Identity();
  78273. this._bone1Mat = BABYLON.Matrix.Identity();
  78274. this._bone2Ang = Math.PI;
  78275. this._maxAngle = Math.PI;
  78276. this._rightHandedSystem = false;
  78277. this._bendAxis = BABYLON.Vector3.Right();
  78278. this._slerping = false;
  78279. this._adjustRoll = 0;
  78280. this._bone2 = bone;
  78281. this._bone1 = bone.getParent();
  78282. if (!this._bone1) {
  78283. return;
  78284. }
  78285. this.mesh = mesh;
  78286. var bonePos = bone.getPosition();
  78287. if (bone.getAbsoluteTransform().determinant() > 0) {
  78288. this._rightHandedSystem = true;
  78289. this._bendAxis.x = 0;
  78290. this._bendAxis.y = 0;
  78291. this._bendAxis.z = -1;
  78292. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78293. this._adjustRoll = Math.PI * .5;
  78294. this._bendAxis.z = 1;
  78295. }
  78296. }
  78297. if (this._bone1.length) {
  78298. var boneScale1 = this._bone1.getScale();
  78299. var boneScale2 = this._bone2.getScale();
  78300. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78301. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78302. }
  78303. else if (this._bone1.children[0]) {
  78304. mesh.computeWorldMatrix(true);
  78305. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78306. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78307. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78308. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78309. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78310. }
  78311. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78312. this.maxAngle = Math.PI;
  78313. if (options) {
  78314. if (options.targetMesh) {
  78315. this.targetMesh = options.targetMesh;
  78316. this.targetMesh.computeWorldMatrix(true);
  78317. }
  78318. if (options.poleTargetMesh) {
  78319. this.poleTargetMesh = options.poleTargetMesh;
  78320. this.poleTargetMesh.computeWorldMatrix(true);
  78321. }
  78322. else if (options.poleTargetBone) {
  78323. this.poleTargetBone = options.poleTargetBone;
  78324. }
  78325. else if (this._bone1.getParent()) {
  78326. this.poleTargetBone = this._bone1.getParent();
  78327. }
  78328. if (options.poleTargetLocalOffset) {
  78329. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78330. }
  78331. if (options.poleAngle) {
  78332. this.poleAngle = options.poleAngle;
  78333. }
  78334. if (options.bendAxis) {
  78335. this._bendAxis.copyFrom(options.bendAxis);
  78336. }
  78337. if (options.maxAngle) {
  78338. this.maxAngle = options.maxAngle;
  78339. }
  78340. if (options.slerpAmount) {
  78341. this.slerpAmount = options.slerpAmount;
  78342. }
  78343. }
  78344. }
  78345. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78346. /**
  78347. * Gets or sets maximum allowed angle
  78348. */
  78349. get: function () {
  78350. return this._maxAngle;
  78351. },
  78352. set: function (value) {
  78353. this._setMaxAngle(value);
  78354. },
  78355. enumerable: true,
  78356. configurable: true
  78357. });
  78358. BoneIKController.prototype._setMaxAngle = function (ang) {
  78359. if (ang < 0) {
  78360. ang = 0;
  78361. }
  78362. if (ang > Math.PI || ang == undefined) {
  78363. ang = Math.PI;
  78364. }
  78365. this._maxAngle = ang;
  78366. var a = this._bone1Length;
  78367. var b = this._bone2Length;
  78368. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78369. };
  78370. /**
  78371. * Force the controller to update the bones
  78372. */
  78373. BoneIKController.prototype.update = function () {
  78374. var bone1 = this._bone1;
  78375. if (!bone1) {
  78376. return;
  78377. }
  78378. var target = this.targetPosition;
  78379. var poleTarget = this.poleTargetPosition;
  78380. var mat1 = BoneIKController._tmpMats[0];
  78381. var mat2 = BoneIKController._tmpMats[1];
  78382. if (this.targetMesh) {
  78383. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78384. }
  78385. if (this.poleTargetBone) {
  78386. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78387. }
  78388. else if (this.poleTargetMesh) {
  78389. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78390. }
  78391. var bonePos = BoneIKController._tmpVecs[0];
  78392. var zaxis = BoneIKController._tmpVecs[1];
  78393. var xaxis = BoneIKController._tmpVecs[2];
  78394. var yaxis = BoneIKController._tmpVecs[3];
  78395. var upAxis = BoneIKController._tmpVecs[4];
  78396. var _tmpQuat = BoneIKController._tmpQuat;
  78397. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78398. poleTarget.subtractToRef(bonePos, upAxis);
  78399. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78400. upAxis.y = 1;
  78401. }
  78402. else {
  78403. upAxis.normalize();
  78404. }
  78405. target.subtractToRef(bonePos, yaxis);
  78406. yaxis.normalize();
  78407. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78408. zaxis.normalize();
  78409. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78410. xaxis.normalize();
  78411. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78412. var a = this._bone1Length;
  78413. var b = this._bone2Length;
  78414. var c = BABYLON.Vector3.Distance(bonePos, target);
  78415. if (this._maxReach > 0) {
  78416. c = Math.min(this._maxReach, c);
  78417. }
  78418. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78419. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78420. if (acosa > 1) {
  78421. acosa = 1;
  78422. }
  78423. if (acosb > 1) {
  78424. acosb = 1;
  78425. }
  78426. if (acosa < -1) {
  78427. acosa = -1;
  78428. }
  78429. if (acosb < -1) {
  78430. acosb = -1;
  78431. }
  78432. var angA = Math.acos(acosa);
  78433. var angB = Math.acos(acosb);
  78434. var angC = -angA - angB;
  78435. if (this._rightHandedSystem) {
  78436. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78437. mat2.multiplyToRef(mat1, mat1);
  78438. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78439. mat2.multiplyToRef(mat1, mat1);
  78440. }
  78441. else {
  78442. var _tmpVec = BoneIKController._tmpVecs[5];
  78443. _tmpVec.copyFrom(this._bendAxis);
  78444. _tmpVec.x *= -1;
  78445. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78446. mat2.multiplyToRef(mat1, mat1);
  78447. }
  78448. if (this.poleAngle) {
  78449. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78450. mat1.multiplyToRef(mat2, mat1);
  78451. }
  78452. if (this._bone1) {
  78453. if (this.slerpAmount < 1) {
  78454. if (!this._slerping) {
  78455. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78456. }
  78457. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78458. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78459. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78460. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78461. this._slerping = true;
  78462. }
  78463. else {
  78464. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78465. this._bone1Mat.copyFrom(mat1);
  78466. this._slerping = false;
  78467. }
  78468. }
  78469. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78470. this._bone2Ang = angC;
  78471. };
  78472. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78473. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78474. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78475. return BoneIKController;
  78476. }());
  78477. BABYLON.BoneIKController = BoneIKController;
  78478. })(BABYLON || (BABYLON = {}));
  78479. //# sourceMappingURL=babylon.boneIKController.js.map
  78480. var BABYLON;
  78481. (function (BABYLON) {
  78482. /**
  78483. * Class used to make a bone look toward a point in space
  78484. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78485. */
  78486. var BoneLookController = /** @class */ (function () {
  78487. /**
  78488. * Create a BoneLookController
  78489. * @param mesh the mesh that the bone belongs to
  78490. * @param bone the bone that will be looking to the target
  78491. * @param target the target Vector3 to look at
  78492. * @param settings optional settings:
  78493. * * maxYaw: the maximum angle the bone will yaw to
  78494. * * minYaw: the minimum angle the bone will yaw to
  78495. * * maxPitch: the maximum angle the bone will pitch to
  78496. * * minPitch: the minimum angle the bone will yaw to
  78497. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78498. * * upAxis: the up axis of the coordinate system
  78499. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78500. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78501. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78502. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78503. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78504. * * adjustRoll: used to make an adjustment to the roll of the bone
  78505. **/
  78506. function BoneLookController(mesh, bone, target, options) {
  78507. /**
  78508. * The up axis of the coordinate system that is used when the bone is rotated
  78509. */
  78510. this.upAxis = BABYLON.Vector3.Up();
  78511. /**
  78512. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78513. */
  78514. this.upAxisSpace = BABYLON.Space.LOCAL;
  78515. /**
  78516. * Used to make an adjustment to the yaw of the bone
  78517. */
  78518. this.adjustYaw = 0;
  78519. /**
  78520. * Used to make an adjustment to the pitch of the bone
  78521. */
  78522. this.adjustPitch = 0;
  78523. /**
  78524. * Used to make an adjustment to the roll of the bone
  78525. */
  78526. this.adjustRoll = 0;
  78527. /**
  78528. * 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)
  78529. */
  78530. this.slerpAmount = 1;
  78531. this._boneQuat = BABYLON.Quaternion.Identity();
  78532. this._slerping = false;
  78533. this._firstFrameSkipped = false;
  78534. this._fowardAxis = BABYLON.Vector3.Forward();
  78535. this.mesh = mesh;
  78536. this.bone = bone;
  78537. this.target = target;
  78538. if (options) {
  78539. if (options.adjustYaw) {
  78540. this.adjustYaw = options.adjustYaw;
  78541. }
  78542. if (options.adjustPitch) {
  78543. this.adjustPitch = options.adjustPitch;
  78544. }
  78545. if (options.adjustRoll) {
  78546. this.adjustRoll = options.adjustRoll;
  78547. }
  78548. if (options.maxYaw != null) {
  78549. this.maxYaw = options.maxYaw;
  78550. }
  78551. else {
  78552. this.maxYaw = Math.PI;
  78553. }
  78554. if (options.minYaw != null) {
  78555. this.minYaw = options.minYaw;
  78556. }
  78557. else {
  78558. this.minYaw = -Math.PI;
  78559. }
  78560. if (options.maxPitch != null) {
  78561. this.maxPitch = options.maxPitch;
  78562. }
  78563. else {
  78564. this.maxPitch = Math.PI;
  78565. }
  78566. if (options.minPitch != null) {
  78567. this.minPitch = options.minPitch;
  78568. }
  78569. else {
  78570. this.minPitch = -Math.PI;
  78571. }
  78572. if (options.slerpAmount != null) {
  78573. this.slerpAmount = options.slerpAmount;
  78574. }
  78575. if (options.upAxis != null) {
  78576. this.upAxis = options.upAxis;
  78577. }
  78578. if (options.upAxisSpace != null) {
  78579. this.upAxisSpace = options.upAxisSpace;
  78580. }
  78581. if (options.yawAxis != null || options.pitchAxis != null) {
  78582. var newYawAxis = BABYLON.Axis.Y;
  78583. var newPitchAxis = BABYLON.Axis.X;
  78584. if (options.yawAxis != null) {
  78585. newYawAxis = options.yawAxis.clone();
  78586. newYawAxis.normalize();
  78587. }
  78588. if (options.pitchAxis != null) {
  78589. newPitchAxis = options.pitchAxis.clone();
  78590. newPitchAxis.normalize();
  78591. }
  78592. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78593. this._transformYawPitch = BABYLON.Matrix.Identity();
  78594. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78595. this._transformYawPitchInv = this._transformYawPitch.clone();
  78596. this._transformYawPitch.invert();
  78597. }
  78598. }
  78599. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78600. this.upAxisSpace = BABYLON.Space.LOCAL;
  78601. }
  78602. }
  78603. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78604. /**
  78605. * Gets or sets the minimum yaw angle that the bone can look to
  78606. */
  78607. get: function () {
  78608. return this._minYaw;
  78609. },
  78610. set: function (value) {
  78611. this._minYaw = value;
  78612. this._minYawSin = Math.sin(value);
  78613. this._minYawCos = Math.cos(value);
  78614. if (this._maxYaw != null) {
  78615. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78616. this._yawRange = this._maxYaw - this._minYaw;
  78617. }
  78618. },
  78619. enumerable: true,
  78620. configurable: true
  78621. });
  78622. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78623. /**
  78624. * Gets or sets the maximum yaw angle that the bone can look to
  78625. */
  78626. get: function () {
  78627. return this._maxYaw;
  78628. },
  78629. set: function (value) {
  78630. this._maxYaw = value;
  78631. this._maxYawSin = Math.sin(value);
  78632. this._maxYawCos = Math.cos(value);
  78633. if (this._minYaw != null) {
  78634. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78635. this._yawRange = this._maxYaw - this._minYaw;
  78636. }
  78637. },
  78638. enumerable: true,
  78639. configurable: true
  78640. });
  78641. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78642. /**
  78643. * Gets or sets the minimum pitch angle that the bone can look to
  78644. */
  78645. get: function () {
  78646. return this._minPitch;
  78647. },
  78648. set: function (value) {
  78649. this._minPitch = value;
  78650. this._minPitchTan = Math.tan(value);
  78651. },
  78652. enumerable: true,
  78653. configurable: true
  78654. });
  78655. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78656. /**
  78657. * Gets or sets the maximum pitch angle that the bone can look to
  78658. */
  78659. get: function () {
  78660. return this._maxPitch;
  78661. },
  78662. set: function (value) {
  78663. this._maxPitch = value;
  78664. this._maxPitchTan = Math.tan(value);
  78665. },
  78666. enumerable: true,
  78667. configurable: true
  78668. });
  78669. /**
  78670. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78671. */
  78672. BoneLookController.prototype.update = function () {
  78673. //skip the first frame when slerping so that the mesh rotation is correct
  78674. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78675. this._firstFrameSkipped = true;
  78676. return;
  78677. }
  78678. var bone = this.bone;
  78679. var bonePos = BoneLookController._tmpVecs[0];
  78680. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78681. var target = this.target;
  78682. var _tmpMat1 = BoneLookController._tmpMats[0];
  78683. var _tmpMat2 = BoneLookController._tmpMats[1];
  78684. var mesh = this.mesh;
  78685. var parentBone = bone.getParent();
  78686. var upAxis = BoneLookController._tmpVecs[1];
  78687. upAxis.copyFrom(this.upAxis);
  78688. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78689. if (this._transformYawPitch) {
  78690. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78691. }
  78692. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78693. }
  78694. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78695. mesh.getDirectionToRef(upAxis, upAxis);
  78696. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78697. upAxis.normalize();
  78698. }
  78699. }
  78700. var checkYaw = false;
  78701. var checkPitch = false;
  78702. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78703. checkYaw = true;
  78704. }
  78705. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78706. checkPitch = true;
  78707. }
  78708. if (checkYaw || checkPitch) {
  78709. var spaceMat = BoneLookController._tmpMats[2];
  78710. var spaceMatInv = BoneLookController._tmpMats[3];
  78711. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78712. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78713. }
  78714. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78715. spaceMat.copyFrom(mesh.getWorldMatrix());
  78716. }
  78717. else {
  78718. var forwardAxis = BoneLookController._tmpVecs[2];
  78719. forwardAxis.copyFrom(this._fowardAxis);
  78720. if (this._transformYawPitch) {
  78721. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78722. }
  78723. if (parentBone) {
  78724. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78725. }
  78726. else {
  78727. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78728. }
  78729. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78730. rightAxis.normalize();
  78731. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78732. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78733. }
  78734. spaceMat.invertToRef(spaceMatInv);
  78735. var xzlen = null;
  78736. if (checkPitch) {
  78737. var localTarget = BoneLookController._tmpVecs[3];
  78738. target.subtractToRef(bonePos, localTarget);
  78739. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78740. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78741. var pitch = Math.atan2(localTarget.y, xzlen);
  78742. var newPitch = pitch;
  78743. if (pitch > this._maxPitch) {
  78744. localTarget.y = this._maxPitchTan * xzlen;
  78745. newPitch = this._maxPitch;
  78746. }
  78747. else if (pitch < this._minPitch) {
  78748. localTarget.y = this._minPitchTan * xzlen;
  78749. newPitch = this._minPitch;
  78750. }
  78751. if (pitch != newPitch) {
  78752. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78753. localTarget.addInPlace(bonePos);
  78754. target = localTarget;
  78755. }
  78756. }
  78757. if (checkYaw) {
  78758. var localTarget = BoneLookController._tmpVecs[4];
  78759. target.subtractToRef(bonePos, localTarget);
  78760. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78761. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78762. var newYaw = yaw;
  78763. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78764. if (xzlen == null) {
  78765. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78766. }
  78767. if (this._yawRange > Math.PI) {
  78768. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78769. localTarget.z = this._maxYawCos * xzlen;
  78770. localTarget.x = this._maxYawSin * xzlen;
  78771. newYaw = this._maxYaw;
  78772. }
  78773. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78774. localTarget.z = this._minYawCos * xzlen;
  78775. localTarget.x = this._minYawSin * xzlen;
  78776. newYaw = this._minYaw;
  78777. }
  78778. }
  78779. else {
  78780. if (yaw > this._maxYaw) {
  78781. localTarget.z = this._maxYawCos * xzlen;
  78782. localTarget.x = this._maxYawSin * xzlen;
  78783. newYaw = this._maxYaw;
  78784. }
  78785. else if (yaw < this._minYaw) {
  78786. localTarget.z = this._minYawCos * xzlen;
  78787. localTarget.x = this._minYawSin * xzlen;
  78788. newYaw = this._minYaw;
  78789. }
  78790. }
  78791. }
  78792. if (this._slerping && this._yawRange > Math.PI) {
  78793. //are we going to be crossing into the min/max region?
  78794. var boneFwd = BoneLookController._tmpVecs[8];
  78795. boneFwd.copyFrom(BABYLON.Axis.Z);
  78796. if (this._transformYawPitch) {
  78797. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78798. }
  78799. var boneRotMat = BoneLookController._tmpMats[4];
  78800. this._boneQuat.toRotationMatrix(boneRotMat);
  78801. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78802. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78803. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78804. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78805. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78806. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78807. if (angBtwTar > angBtwMidYaw) {
  78808. if (xzlen == null) {
  78809. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78810. }
  78811. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78812. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78813. if (angBtwMin < angBtwMax) {
  78814. newYaw = boneYaw + Math.PI * .75;
  78815. localTarget.z = Math.cos(newYaw) * xzlen;
  78816. localTarget.x = Math.sin(newYaw) * xzlen;
  78817. }
  78818. else {
  78819. newYaw = boneYaw - Math.PI * .75;
  78820. localTarget.z = Math.cos(newYaw) * xzlen;
  78821. localTarget.x = Math.sin(newYaw) * xzlen;
  78822. }
  78823. }
  78824. }
  78825. if (yaw != newYaw) {
  78826. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78827. localTarget.addInPlace(bonePos);
  78828. target = localTarget;
  78829. }
  78830. }
  78831. }
  78832. var zaxis = BoneLookController._tmpVecs[5];
  78833. var xaxis = BoneLookController._tmpVecs[6];
  78834. var yaxis = BoneLookController._tmpVecs[7];
  78835. var _tmpQuat = BoneLookController._tmpQuat;
  78836. target.subtractToRef(bonePos, zaxis);
  78837. zaxis.normalize();
  78838. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78839. xaxis.normalize();
  78840. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78841. yaxis.normalize();
  78842. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78843. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78844. return;
  78845. }
  78846. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78847. return;
  78848. }
  78849. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78850. return;
  78851. }
  78852. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78853. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78854. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78855. }
  78856. if (this.slerpAmount < 1) {
  78857. if (!this._slerping) {
  78858. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78859. }
  78860. if (this._transformYawPitch) {
  78861. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78862. }
  78863. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78864. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78865. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78866. this._slerping = true;
  78867. }
  78868. else {
  78869. if (this._transformYawPitch) {
  78870. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78871. }
  78872. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78873. this._slerping = false;
  78874. }
  78875. };
  78876. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78877. var angDiff = ang2 - ang1;
  78878. angDiff %= Math.PI * 2;
  78879. if (angDiff > Math.PI) {
  78880. angDiff -= Math.PI * 2;
  78881. }
  78882. else if (angDiff < -Math.PI) {
  78883. angDiff += Math.PI * 2;
  78884. }
  78885. return angDiff;
  78886. };
  78887. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78888. ang1 %= (2 * Math.PI);
  78889. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78890. ang2 %= (2 * Math.PI);
  78891. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78892. var ab = 0;
  78893. if (ang1 < ang2) {
  78894. ab = ang2 - ang1;
  78895. }
  78896. else {
  78897. ab = ang1 - ang2;
  78898. }
  78899. if (ab > Math.PI) {
  78900. ab = Math.PI * 2 - ab;
  78901. }
  78902. return ab;
  78903. };
  78904. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78905. ang %= (2 * Math.PI);
  78906. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78907. ang1 %= (2 * Math.PI);
  78908. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78909. ang2 %= (2 * Math.PI);
  78910. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78911. if (ang1 < ang2) {
  78912. if (ang > ang1 && ang < ang2) {
  78913. return true;
  78914. }
  78915. }
  78916. else {
  78917. if (ang > ang2 && ang < ang1) {
  78918. return true;
  78919. }
  78920. }
  78921. return false;
  78922. };
  78923. 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()];
  78924. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  78925. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78926. return BoneLookController;
  78927. }());
  78928. BABYLON.BoneLookController = BoneLookController;
  78929. })(BABYLON || (BABYLON = {}));
  78930. //# sourceMappingURL=babylon.boneLookController.js.map
  78931. var BABYLON;
  78932. (function (BABYLON) {
  78933. /**
  78934. * Class used to handle skinning animations
  78935. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78936. */
  78937. var Skeleton = /** @class */ (function () {
  78938. /**
  78939. * Creates a new skeleton
  78940. * @param name defines the skeleton name
  78941. * @param id defines the skeleton Id
  78942. * @param scene defines the hosting scene
  78943. */
  78944. function Skeleton(
  78945. /** defines the skeleton name */
  78946. name,
  78947. /** defines the skeleton Id */
  78948. id, scene) {
  78949. this.name = name;
  78950. this.id = id;
  78951. /**
  78952. * Gets the list of child bones
  78953. */
  78954. this.bones = new Array();
  78955. /**
  78956. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  78957. */
  78958. this.needInitialSkinMatrix = false;
  78959. this._isDirty = true;
  78960. this._meshesWithPoseMatrix = new Array();
  78961. this._identity = BABYLON.Matrix.Identity();
  78962. this._ranges = {};
  78963. this._lastAbsoluteTransformsUpdateId = -1;
  78964. /**
  78965. * Specifies if the skeleton should be serialized
  78966. */
  78967. this.doNotSerialize = false;
  78968. this._animationPropertiesOverride = null;
  78969. // Events
  78970. /**
  78971. * An observable triggered before computing the skeleton's matrices
  78972. */
  78973. this.onBeforeComputeObservable = new BABYLON.Observable();
  78974. this.bones = [];
  78975. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78976. scene.skeletons.push(this);
  78977. //make sure it will recalculate the matrix next time prepare is called.
  78978. this._isDirty = true;
  78979. }
  78980. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  78981. /**
  78982. * Gets or sets the animation properties override
  78983. */
  78984. get: function () {
  78985. if (!this._animationPropertiesOverride) {
  78986. return this._scene.animationPropertiesOverride;
  78987. }
  78988. return this._animationPropertiesOverride;
  78989. },
  78990. set: function (value) {
  78991. this._animationPropertiesOverride = value;
  78992. },
  78993. enumerable: true,
  78994. configurable: true
  78995. });
  78996. // Members
  78997. /**
  78998. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  78999. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79000. * @returns a Float32Array containing matrices data
  79001. */
  79002. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79003. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79004. return mesh._bonesTransformMatrices;
  79005. }
  79006. if (!this._transformMatrices) {
  79007. this.prepare();
  79008. }
  79009. return this._transformMatrices;
  79010. };
  79011. /**
  79012. * Gets the current hosting scene
  79013. * @returns a scene object
  79014. */
  79015. Skeleton.prototype.getScene = function () {
  79016. return this._scene;
  79017. };
  79018. // Methods
  79019. /**
  79020. * Gets a string representing the current skeleton data
  79021. * @param fullDetails defines a boolean indicating if we want a verbose version
  79022. * @returns a string representing the current skeleton data
  79023. */
  79024. Skeleton.prototype.toString = function (fullDetails) {
  79025. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79026. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79027. if (fullDetails) {
  79028. ret += ", Ranges: {";
  79029. var first = true;
  79030. for (var name_1 in this._ranges) {
  79031. if (first) {
  79032. ret += ", ";
  79033. first = false;
  79034. }
  79035. ret += name_1;
  79036. }
  79037. ret += "}";
  79038. }
  79039. return ret;
  79040. };
  79041. /**
  79042. * Get bone's index searching by name
  79043. * @param name defines bone's name to search for
  79044. * @return the indice of the bone. Returns -1 if not found
  79045. */
  79046. Skeleton.prototype.getBoneIndexByName = function (name) {
  79047. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79048. if (this.bones[boneIndex].name === name) {
  79049. return boneIndex;
  79050. }
  79051. }
  79052. return -1;
  79053. };
  79054. /**
  79055. * Creater a new animation range
  79056. * @param name defines the name of the range
  79057. * @param from defines the start key
  79058. * @param to defines the end key
  79059. */
  79060. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79061. // check name not already in use
  79062. if (!this._ranges[name]) {
  79063. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79064. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79065. if (this.bones[i].animations[0]) {
  79066. this.bones[i].animations[0].createRange(name, from, to);
  79067. }
  79068. }
  79069. }
  79070. };
  79071. /**
  79072. * Delete a specific animation range
  79073. * @param name defines the name of the range
  79074. * @param deleteFrames defines if frames must be removed as well
  79075. */
  79076. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79077. if (deleteFrames === void 0) { deleteFrames = true; }
  79078. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79079. if (this.bones[i].animations[0]) {
  79080. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79081. }
  79082. }
  79083. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79084. };
  79085. /**
  79086. * Gets a specific animation range
  79087. * @param name defines the name of the range to look for
  79088. * @returns the requested animation range or null if not found
  79089. */
  79090. Skeleton.prototype.getAnimationRange = function (name) {
  79091. return this._ranges[name];
  79092. };
  79093. /**
  79094. * Gets the list of all animation ranges defined on this skeleton
  79095. * @returns an array
  79096. */
  79097. Skeleton.prototype.getAnimationRanges = function () {
  79098. var animationRanges = [];
  79099. var name;
  79100. var i = 0;
  79101. for (name in this._ranges) {
  79102. animationRanges[i] = this._ranges[name];
  79103. i++;
  79104. }
  79105. return animationRanges;
  79106. };
  79107. /**
  79108. * Copy animation range from a source skeleton.
  79109. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79110. * @param source defines the source skeleton
  79111. * @param name defines the name of the range to copy
  79112. * @param rescaleAsRequired defines if rescaling must be applied if required
  79113. * @returns true if operation was successful
  79114. */
  79115. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79116. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79117. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79118. return false;
  79119. }
  79120. var ret = true;
  79121. var frameOffset = this._getHighestAnimationFrame() + 1;
  79122. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79123. var boneDict = {};
  79124. var sourceBones = source.bones;
  79125. var nBones;
  79126. var i;
  79127. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79128. boneDict[sourceBones[i].name] = sourceBones[i];
  79129. }
  79130. if (this.bones.length !== sourceBones.length) {
  79131. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79132. ret = false;
  79133. }
  79134. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79135. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79136. var boneName = this.bones[i].name;
  79137. var sourceBone = boneDict[boneName];
  79138. if (sourceBone) {
  79139. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79140. }
  79141. else {
  79142. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79143. ret = false;
  79144. }
  79145. }
  79146. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79147. var range = source.getAnimationRange(name);
  79148. if (range) {
  79149. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79150. }
  79151. return ret;
  79152. };
  79153. /**
  79154. * Forces the skeleton to go to rest pose
  79155. */
  79156. Skeleton.prototype.returnToRest = function () {
  79157. for (var index = 0; index < this.bones.length; index++) {
  79158. this.bones[index].returnToRest();
  79159. }
  79160. };
  79161. Skeleton.prototype._getHighestAnimationFrame = function () {
  79162. var ret = 0;
  79163. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79164. if (this.bones[i].animations[0]) {
  79165. var highest = this.bones[i].animations[0].getHighestFrame();
  79166. if (ret < highest) {
  79167. ret = highest;
  79168. }
  79169. }
  79170. }
  79171. return ret;
  79172. };
  79173. /**
  79174. * Begin a specific animation range
  79175. * @param name defines the name of the range to start
  79176. * @param loop defines if looping must be turned on (false by default)
  79177. * @param speedRatio defines the speed ratio to apply (1 by default)
  79178. * @param onAnimationEnd defines a callback which will be called when animation will end
  79179. * @returns a new animatable
  79180. */
  79181. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79182. var range = this.getAnimationRange(name);
  79183. if (!range) {
  79184. return null;
  79185. }
  79186. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79187. };
  79188. /** @hidden */
  79189. Skeleton.prototype._markAsDirty = function () {
  79190. this._isDirty = true;
  79191. };
  79192. /** @hidden */
  79193. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79194. this._meshesWithPoseMatrix.push(mesh);
  79195. };
  79196. /** @hidden */
  79197. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79198. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79199. if (index > -1) {
  79200. this._meshesWithPoseMatrix.splice(index, 1);
  79201. }
  79202. };
  79203. /** @hidden */
  79204. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79205. this.onBeforeComputeObservable.notifyObservers(this);
  79206. for (var index = 0; index < this.bones.length; index++) {
  79207. var bone = this.bones[index];
  79208. var parentBone = bone.getParent();
  79209. if (parentBone) {
  79210. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79211. }
  79212. else {
  79213. if (initialSkinMatrix) {
  79214. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79215. }
  79216. else {
  79217. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79218. }
  79219. }
  79220. if (bone._index !== -1) {
  79221. var mappedIndex = bone._index === null ? index : bone._index;
  79222. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79223. }
  79224. }
  79225. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79226. };
  79227. /**
  79228. * Build all resources required to render a skeleton
  79229. */
  79230. Skeleton.prototype.prepare = function () {
  79231. if (!this._isDirty) {
  79232. return;
  79233. }
  79234. if (this.needInitialSkinMatrix) {
  79235. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79236. var mesh = this._meshesWithPoseMatrix[index];
  79237. var poseMatrix = mesh.getPoseMatrix();
  79238. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79239. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79240. }
  79241. if (this._synchronizedWithMesh !== mesh) {
  79242. this._synchronizedWithMesh = mesh;
  79243. // Prepare bones
  79244. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79245. var bone = this.bones[boneIndex];
  79246. if (!bone.getParent()) {
  79247. var matrix = bone.getBaseMatrix();
  79248. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79249. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79250. }
  79251. }
  79252. }
  79253. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79254. }
  79255. }
  79256. else {
  79257. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79258. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79259. }
  79260. this._computeTransformMatrices(this._transformMatrices, null);
  79261. }
  79262. this._isDirty = false;
  79263. this._scene._activeBones.addCount(this.bones.length, false);
  79264. };
  79265. /**
  79266. * Gets the list of animatables currently running for this skeleton
  79267. * @returns an array of animatables
  79268. */
  79269. Skeleton.prototype.getAnimatables = function () {
  79270. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79271. this._animatables = [];
  79272. for (var index = 0; index < this.bones.length; index++) {
  79273. this._animatables.push(this.bones[index]);
  79274. }
  79275. }
  79276. return this._animatables;
  79277. };
  79278. /**
  79279. * Clone the current skeleton
  79280. * @param name defines the name of the new skeleton
  79281. * @param id defines the id of the enw skeleton
  79282. * @returns the new skeleton
  79283. */
  79284. Skeleton.prototype.clone = function (name, id) {
  79285. var result = new Skeleton(name, id || name, this._scene);
  79286. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79287. for (var index = 0; index < this.bones.length; index++) {
  79288. var source = this.bones[index];
  79289. var parentBone = null;
  79290. var parent_1 = source.getParent();
  79291. if (parent_1) {
  79292. var parentIndex = this.bones.indexOf(parent_1);
  79293. parentBone = result.bones[parentIndex];
  79294. }
  79295. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79296. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79297. }
  79298. if (this._ranges) {
  79299. result._ranges = {};
  79300. for (var rangeName in this._ranges) {
  79301. var range = this._ranges[rangeName];
  79302. if (range) {
  79303. result._ranges[rangeName] = range.clone();
  79304. }
  79305. }
  79306. }
  79307. this._isDirty = true;
  79308. return result;
  79309. };
  79310. /**
  79311. * Enable animation blending for this skeleton
  79312. * @param blendingSpeed defines the blending speed to apply
  79313. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79314. */
  79315. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79316. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79317. this.bones.forEach(function (bone) {
  79318. bone.animations.forEach(function (animation) {
  79319. animation.enableBlending = true;
  79320. animation.blendingSpeed = blendingSpeed;
  79321. });
  79322. });
  79323. };
  79324. /**
  79325. * Releases all resources associated with the current skeleton
  79326. */
  79327. Skeleton.prototype.dispose = function () {
  79328. this._meshesWithPoseMatrix = [];
  79329. // Animations
  79330. this.getScene().stopAnimation(this);
  79331. // Remove from scene
  79332. this.getScene().removeSkeleton(this);
  79333. };
  79334. /**
  79335. * Serialize the skeleton in a JSON object
  79336. * @returns a JSON object
  79337. */
  79338. Skeleton.prototype.serialize = function () {
  79339. var serializationObject = {};
  79340. serializationObject.name = this.name;
  79341. serializationObject.id = this.id;
  79342. if (this.dimensionsAtRest) {
  79343. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79344. }
  79345. serializationObject.bones = [];
  79346. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79347. for (var index = 0; index < this.bones.length; index++) {
  79348. var bone = this.bones[index];
  79349. var parent_2 = bone.getParent();
  79350. var serializedBone = {
  79351. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79352. name: bone.name,
  79353. matrix: bone.getBaseMatrix().toArray(),
  79354. rest: bone.getRestPose().toArray()
  79355. };
  79356. serializationObject.bones.push(serializedBone);
  79357. if (bone.length) {
  79358. serializedBone.length = bone.length;
  79359. }
  79360. if (bone.animations && bone.animations.length > 0) {
  79361. serializedBone.animation = bone.animations[0].serialize();
  79362. }
  79363. serializationObject.ranges = [];
  79364. for (var name in this._ranges) {
  79365. var source = this._ranges[name];
  79366. if (!source) {
  79367. continue;
  79368. }
  79369. var range = {};
  79370. range.name = name;
  79371. range.from = source.from;
  79372. range.to = source.to;
  79373. serializationObject.ranges.push(range);
  79374. }
  79375. }
  79376. return serializationObject;
  79377. };
  79378. /**
  79379. * Creates a new skeleton from serialized data
  79380. * @param parsedSkeleton defines the serialized data
  79381. * @param scene defines the hosting scene
  79382. * @returns a new skeleton
  79383. */
  79384. Skeleton.Parse = function (parsedSkeleton, scene) {
  79385. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79386. if (parsedSkeleton.dimensionsAtRest) {
  79387. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79388. }
  79389. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79390. var index;
  79391. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79392. var parsedBone = parsedSkeleton.bones[index];
  79393. var parentBone = null;
  79394. if (parsedBone.parentBoneIndex > -1) {
  79395. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79396. }
  79397. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79398. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79399. if (parsedBone.length) {
  79400. bone.length = parsedBone.length;
  79401. }
  79402. if (parsedBone.animation) {
  79403. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79404. }
  79405. }
  79406. // placed after bones, so createAnimationRange can cascade down
  79407. if (parsedSkeleton.ranges) {
  79408. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79409. var data = parsedSkeleton.ranges[index];
  79410. skeleton.createAnimationRange(data.name, data.from, data.to);
  79411. }
  79412. }
  79413. return skeleton;
  79414. };
  79415. /**
  79416. * Compute all node absolute transforms
  79417. * @param forceUpdate defines if computation must be done even if cache is up to date
  79418. */
  79419. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79420. if (forceUpdate === void 0) { forceUpdate = false; }
  79421. var renderId = this._scene.getRenderId();
  79422. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79423. this.bones[0].computeAbsoluteTransforms();
  79424. this._lastAbsoluteTransformsUpdateId = renderId;
  79425. }
  79426. };
  79427. /**
  79428. * Gets the root pose matrix
  79429. * @returns a matrix
  79430. */
  79431. Skeleton.prototype.getPoseMatrix = function () {
  79432. var poseMatrix = null;
  79433. if (this._meshesWithPoseMatrix.length > 0) {
  79434. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79435. }
  79436. return poseMatrix;
  79437. };
  79438. /**
  79439. * Sorts bones per internal index
  79440. */
  79441. Skeleton.prototype.sortBones = function () {
  79442. var bones = new Array();
  79443. var visited = new Array(this.bones.length);
  79444. for (var index = 0; index < this.bones.length; index++) {
  79445. this._sortBones(index, bones, visited);
  79446. }
  79447. this.bones = bones;
  79448. };
  79449. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79450. if (visited[index]) {
  79451. return;
  79452. }
  79453. visited[index] = true;
  79454. var bone = this.bones[index];
  79455. if (bone._index === undefined) {
  79456. bone._index = index;
  79457. }
  79458. var parentBone = bone.getParent();
  79459. if (parentBone) {
  79460. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79461. }
  79462. bones.push(bone);
  79463. };
  79464. return Skeleton;
  79465. }());
  79466. BABYLON.Skeleton = Skeleton;
  79467. })(BABYLON || (BABYLON = {}));
  79468. //# sourceMappingURL=babylon.skeleton.js.map
  79469. var BABYLON;
  79470. (function (BABYLON) {
  79471. var SphericalPolynomial = /** @class */ (function () {
  79472. function SphericalPolynomial() {
  79473. this.x = BABYLON.Vector3.Zero();
  79474. this.y = BABYLON.Vector3.Zero();
  79475. this.z = BABYLON.Vector3.Zero();
  79476. this.xx = BABYLON.Vector3.Zero();
  79477. this.yy = BABYLON.Vector3.Zero();
  79478. this.zz = BABYLON.Vector3.Zero();
  79479. this.xy = BABYLON.Vector3.Zero();
  79480. this.yz = BABYLON.Vector3.Zero();
  79481. this.zx = BABYLON.Vector3.Zero();
  79482. }
  79483. SphericalPolynomial.prototype.addAmbient = function (color) {
  79484. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79485. this.xx = this.xx.add(colorVector);
  79486. this.yy = this.yy.add(colorVector);
  79487. this.zz = this.zz.add(colorVector);
  79488. };
  79489. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79490. var result = new SphericalPolynomial();
  79491. result.x = harmonics.L11.scale(1.02333);
  79492. result.y = harmonics.L1_1.scale(1.02333);
  79493. result.z = harmonics.L10.scale(1.02333);
  79494. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79495. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79496. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79497. result.yz = harmonics.L2_1.scale(0.858086);
  79498. result.zx = harmonics.L21.scale(0.858086);
  79499. result.xy = harmonics.L2_2.scale(0.858086);
  79500. result.scale(1.0 / Math.PI);
  79501. return result;
  79502. };
  79503. SphericalPolynomial.prototype.scale = function (scale) {
  79504. this.x = this.x.scale(scale);
  79505. this.y = this.y.scale(scale);
  79506. this.z = this.z.scale(scale);
  79507. this.xx = this.xx.scale(scale);
  79508. this.yy = this.yy.scale(scale);
  79509. this.zz = this.zz.scale(scale);
  79510. this.yz = this.yz.scale(scale);
  79511. this.zx = this.zx.scale(scale);
  79512. this.xy = this.xy.scale(scale);
  79513. };
  79514. return SphericalPolynomial;
  79515. }());
  79516. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79517. var SphericalHarmonics = /** @class */ (function () {
  79518. function SphericalHarmonics() {
  79519. this.L00 = BABYLON.Vector3.Zero();
  79520. this.L1_1 = BABYLON.Vector3.Zero();
  79521. this.L10 = BABYLON.Vector3.Zero();
  79522. this.L11 = BABYLON.Vector3.Zero();
  79523. this.L2_2 = BABYLON.Vector3.Zero();
  79524. this.L2_1 = BABYLON.Vector3.Zero();
  79525. this.L20 = BABYLON.Vector3.Zero();
  79526. this.L21 = BABYLON.Vector3.Zero();
  79527. this.L22 = BABYLON.Vector3.Zero();
  79528. }
  79529. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79530. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79531. var c = colorVector.scale(deltaSolidAngle);
  79532. this.L00 = this.L00.add(c.scale(0.282095));
  79533. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79534. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79535. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79536. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79537. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79538. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79539. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79540. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79541. };
  79542. SphericalHarmonics.prototype.scale = function (scale) {
  79543. this.L00 = this.L00.scale(scale);
  79544. this.L1_1 = this.L1_1.scale(scale);
  79545. this.L10 = this.L10.scale(scale);
  79546. this.L11 = this.L11.scale(scale);
  79547. this.L2_2 = this.L2_2.scale(scale);
  79548. this.L2_1 = this.L2_1.scale(scale);
  79549. this.L20 = this.L20.scale(scale);
  79550. this.L21 = this.L21.scale(scale);
  79551. this.L22 = this.L22.scale(scale);
  79552. };
  79553. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79554. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79555. //
  79556. // E_lm = A_l * L_lm
  79557. //
  79558. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79559. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79560. // the scaling factors are given in equation 9.
  79561. // Constant (Band 0)
  79562. this.L00 = this.L00.scale(3.141593);
  79563. // Linear (Band 1)
  79564. this.L1_1 = this.L1_1.scale(2.094395);
  79565. this.L10 = this.L10.scale(2.094395);
  79566. this.L11 = this.L11.scale(2.094395);
  79567. // Quadratic (Band 2)
  79568. this.L2_2 = this.L2_2.scale(0.785398);
  79569. this.L2_1 = this.L2_1.scale(0.785398);
  79570. this.L20 = this.L20.scale(0.785398);
  79571. this.L21 = this.L21.scale(0.785398);
  79572. this.L22 = this.L22.scale(0.785398);
  79573. };
  79574. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79575. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79576. // L = (1/pi) * E * rho
  79577. //
  79578. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79579. this.scale(1.0 / Math.PI);
  79580. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79581. // (The pixel shader must apply albedo after texture fetches, etc).
  79582. };
  79583. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79584. var result = new SphericalHarmonics();
  79585. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79586. result.L1_1 = polynomial.y.scale(0.977204);
  79587. result.L10 = polynomial.z.scale(0.977204);
  79588. result.L11 = polynomial.x.scale(0.977204);
  79589. result.L2_2 = polynomial.xy.scale(1.16538);
  79590. result.L2_1 = polynomial.yz.scale(1.16538);
  79591. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79592. result.L21 = polynomial.zx.scale(1.16538);
  79593. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79594. result.scale(Math.PI);
  79595. return result;
  79596. };
  79597. return SphericalHarmonics;
  79598. }());
  79599. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79600. })(BABYLON || (BABYLON = {}));
  79601. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79602. var BABYLON;
  79603. (function (BABYLON) {
  79604. var FileFaceOrientation = /** @class */ (function () {
  79605. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79606. this.name = name;
  79607. this.worldAxisForNormal = worldAxisForNormal;
  79608. this.worldAxisForFileX = worldAxisForFileX;
  79609. this.worldAxisForFileY = worldAxisForFileY;
  79610. }
  79611. return FileFaceOrientation;
  79612. }());
  79613. ;
  79614. /**
  79615. * Helper class dealing with the extraction of spherical polynomial dataArray
  79616. * from a cube map.
  79617. */
  79618. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79619. function CubeMapToSphericalPolynomialTools() {
  79620. }
  79621. /**
  79622. * Converts a texture to the according Spherical Polynomial data.
  79623. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79624. *
  79625. * @param texture The texture to extract the information from.
  79626. * @return The Spherical Polynomial data.
  79627. */
  79628. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79629. if (!texture.isCube) {
  79630. // Only supports cube Textures currently.
  79631. return null;
  79632. }
  79633. var size = texture.getSize().width;
  79634. var right = texture.readPixels(0);
  79635. var left = texture.readPixels(1);
  79636. var up;
  79637. var down;
  79638. if (texture.isRenderTarget) {
  79639. up = texture.readPixels(3);
  79640. down = texture.readPixels(2);
  79641. }
  79642. else {
  79643. up = texture.readPixels(2);
  79644. down = texture.readPixels(3);
  79645. }
  79646. var front = texture.readPixels(4);
  79647. var back = texture.readPixels(5);
  79648. var gammaSpace = texture.gammaSpace;
  79649. // Always read as RGBA.
  79650. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79651. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79652. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79653. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79654. }
  79655. var cubeInfo = {
  79656. size: size,
  79657. right: right,
  79658. left: left,
  79659. up: up,
  79660. down: down,
  79661. front: front,
  79662. back: back,
  79663. format: format,
  79664. type: type,
  79665. gammaSpace: gammaSpace,
  79666. };
  79667. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79668. };
  79669. /**
  79670. * Converts a cubemap to the according Spherical Polynomial data.
  79671. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79672. *
  79673. * @param cubeInfo The Cube map to extract the information from.
  79674. * @return The Spherical Polynomial data.
  79675. */
  79676. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79677. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79678. var totalSolidAngle = 0.0;
  79679. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79680. var du = 2.0 / cubeInfo.size;
  79681. var dv = du;
  79682. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79683. var minUV = du * 0.5 - 1.0;
  79684. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79685. var fileFace = this.FileFaces[faceIndex];
  79686. var dataArray = cubeInfo[fileFace.name];
  79687. var v = minUV;
  79688. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79689. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79690. // Because SP is still linear, so summation is fine in that basis.
  79691. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79692. for (var y = 0; y < cubeInfo.size; y++) {
  79693. var u = minUV;
  79694. for (var x = 0; x < cubeInfo.size; x++) {
  79695. // World direction (not normalised)
  79696. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79697. worldDirection.normalize();
  79698. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79699. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79700. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79701. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79702. // Handle Integer types.
  79703. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79704. r /= 255;
  79705. g /= 255;
  79706. b /= 255;
  79707. }
  79708. // Handle Gamma space textures.
  79709. if (cubeInfo.gammaSpace) {
  79710. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79711. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79712. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79713. }
  79714. var color = new BABYLON.Color3(r, g, b);
  79715. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79716. totalSolidAngle += deltaSolidAngle;
  79717. u += du;
  79718. }
  79719. v += dv;
  79720. }
  79721. }
  79722. // Solid angle for entire sphere is 4*pi
  79723. var sphereSolidAngle = 4.0 * Math.PI;
  79724. // Adjust the solid angle to allow for how many faces we processed.
  79725. var facesProcessed = 6.0;
  79726. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79727. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79728. // This is needed because the numerical integration over the cube uses a
  79729. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79730. // and also to compensate for accumulative error due to float precision in the summation.
  79731. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79732. sphericalHarmonics.scale(correctionFactor);
  79733. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79734. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79735. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79736. };
  79737. CubeMapToSphericalPolynomialTools.FileFaces = [
  79738. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79739. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79740. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79741. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79742. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79743. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79744. ];
  79745. return CubeMapToSphericalPolynomialTools;
  79746. }());
  79747. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79748. })(BABYLON || (BABYLON = {}));
  79749. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79750. var BABYLON;
  79751. (function (BABYLON) {
  79752. /**
  79753. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79754. */
  79755. var PanoramaToCubeMapTools = /** @class */ (function () {
  79756. function PanoramaToCubeMapTools() {
  79757. }
  79758. /**
  79759. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79760. *
  79761. * @param float32Array The source data.
  79762. * @param inputWidth The width of the input panorama.
  79763. * @param inputhHeight The height of the input panorama.
  79764. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79765. * @return The cubemap data
  79766. */
  79767. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79768. if (!float32Array) {
  79769. throw "ConvertPanoramaToCubemap: input cannot be null";
  79770. }
  79771. if (float32Array.length != inputWidth * inputHeight * 3) {
  79772. throw "ConvertPanoramaToCubemap: input size is wrong";
  79773. }
  79774. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79775. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79776. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79777. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79778. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79779. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79780. return {
  79781. front: textureFront,
  79782. back: textureBack,
  79783. left: textureLeft,
  79784. right: textureRight,
  79785. up: textureUp,
  79786. down: textureDown,
  79787. size: size,
  79788. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79789. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79790. gammaSpace: false,
  79791. };
  79792. };
  79793. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79794. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79795. var textureArray = new Float32Array(buffer);
  79796. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79797. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79798. var dy = 1 / texSize;
  79799. var fy = 0;
  79800. for (var y = 0; y < texSize; y++) {
  79801. var xv1 = faceData[0];
  79802. var xv2 = faceData[2];
  79803. for (var x = 0; x < texSize; x++) {
  79804. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79805. v.normalize();
  79806. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79807. // 3 channels per pixels
  79808. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79809. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79810. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79811. xv1 = xv1.add(rotDX1);
  79812. xv2 = xv2.add(rotDX2);
  79813. }
  79814. fy += dy;
  79815. }
  79816. return textureArray;
  79817. };
  79818. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79819. var theta = Math.atan2(vDir.z, vDir.x);
  79820. var phi = Math.acos(vDir.y);
  79821. while (theta < -Math.PI)
  79822. theta += 2 * Math.PI;
  79823. while (theta > Math.PI)
  79824. theta -= 2 * Math.PI;
  79825. var dx = theta / Math.PI;
  79826. var dy = phi / Math.PI;
  79827. // recenter.
  79828. dx = dx * 0.5 + 0.5;
  79829. var px = Math.round(dx * inputWidth);
  79830. if (px < 0)
  79831. px = 0;
  79832. else if (px >= inputWidth)
  79833. px = inputWidth - 1;
  79834. var py = Math.round(dy * inputHeight);
  79835. if (py < 0)
  79836. py = 0;
  79837. else if (py >= inputHeight)
  79838. py = inputHeight - 1;
  79839. var inputY = (inputHeight - py - 1);
  79840. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79841. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79842. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79843. return {
  79844. r: r,
  79845. g: g,
  79846. b: b
  79847. };
  79848. };
  79849. PanoramaToCubeMapTools.FACE_FRONT = [
  79850. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79851. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79852. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79853. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79854. ];
  79855. PanoramaToCubeMapTools.FACE_BACK = [
  79856. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79857. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79858. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79859. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79860. ];
  79861. PanoramaToCubeMapTools.FACE_RIGHT = [
  79862. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79863. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79864. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79865. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79866. ];
  79867. PanoramaToCubeMapTools.FACE_LEFT = [
  79868. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79869. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79870. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79871. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79872. ];
  79873. PanoramaToCubeMapTools.FACE_DOWN = [
  79874. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79875. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79876. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79877. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79878. ];
  79879. PanoramaToCubeMapTools.FACE_UP = [
  79880. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79881. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79882. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79883. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79884. ];
  79885. return PanoramaToCubeMapTools;
  79886. }());
  79887. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79888. })(BABYLON || (BABYLON = {}));
  79889. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79890. var BABYLON;
  79891. (function (BABYLON) {
  79892. ;
  79893. /**
  79894. * This groups tools to convert HDR texture to native colors array.
  79895. */
  79896. var HDRTools = /** @class */ (function () {
  79897. function HDRTools() {
  79898. }
  79899. HDRTools.Ldexp = function (mantissa, exponent) {
  79900. if (exponent > 1023) {
  79901. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79902. }
  79903. if (exponent < -1074) {
  79904. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79905. }
  79906. return mantissa * Math.pow(2, exponent);
  79907. };
  79908. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79909. if (exponent > 0) { /*nonzero pixel*/
  79910. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79911. float32array[index + 0] = red * exponent;
  79912. float32array[index + 1] = green * exponent;
  79913. float32array[index + 2] = blue * exponent;
  79914. }
  79915. else {
  79916. float32array[index + 0] = 0;
  79917. float32array[index + 1] = 0;
  79918. float32array[index + 2] = 0;
  79919. }
  79920. };
  79921. HDRTools.readStringLine = function (uint8array, startIndex) {
  79922. var line = "";
  79923. var character = "";
  79924. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  79925. character = String.fromCharCode(uint8array[i]);
  79926. if (character == "\n") {
  79927. break;
  79928. }
  79929. line += character;
  79930. }
  79931. return line;
  79932. };
  79933. /**
  79934. * Reads header information from an RGBE texture stored in a native array.
  79935. * More information on this format are available here:
  79936. * https://en.wikipedia.org/wiki/RGBE_image_format
  79937. *
  79938. * @param uint8array The binary file stored in native array.
  79939. * @return The header information.
  79940. */
  79941. HDRTools.RGBE_ReadHeader = function (uint8array) {
  79942. var height = 0;
  79943. var width = 0;
  79944. var line = this.readStringLine(uint8array, 0);
  79945. if (line[0] != '#' || line[1] != '?') {
  79946. throw "Bad HDR Format.";
  79947. }
  79948. var endOfHeader = false;
  79949. var findFormat = false;
  79950. var lineIndex = 0;
  79951. do {
  79952. lineIndex += (line.length + 1);
  79953. line = this.readStringLine(uint8array, lineIndex);
  79954. if (line == "FORMAT=32-bit_rle_rgbe") {
  79955. findFormat = true;
  79956. }
  79957. else if (line.length == 0) {
  79958. endOfHeader = true;
  79959. }
  79960. } while (!endOfHeader);
  79961. if (!findFormat) {
  79962. throw "HDR Bad header format, unsupported FORMAT";
  79963. }
  79964. lineIndex += (line.length + 1);
  79965. line = this.readStringLine(uint8array, lineIndex);
  79966. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  79967. var match = sizeRegexp.exec(line);
  79968. // TODO. Support +Y and -X if needed.
  79969. if (!match || match.length < 3) {
  79970. throw "HDR Bad header format, no size";
  79971. }
  79972. width = parseInt(match[2]);
  79973. height = parseInt(match[1]);
  79974. if (width < 8 || width > 0x7fff) {
  79975. throw "HDR Bad header format, unsupported size";
  79976. }
  79977. lineIndex += (line.length + 1);
  79978. return {
  79979. height: height,
  79980. width: width,
  79981. dataPosition: lineIndex
  79982. };
  79983. };
  79984. /**
  79985. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  79986. * This RGBE texture needs to store the information as a panorama.
  79987. *
  79988. * More information on this format are available here:
  79989. * https://en.wikipedia.org/wiki/RGBE_image_format
  79990. *
  79991. * @param buffer The binary file stored in an array buffer.
  79992. * @param size The expected size of the extracted cubemap.
  79993. * @return The Cube Map information.
  79994. */
  79995. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  79996. var uint8array = new Uint8Array(buffer);
  79997. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  79998. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79999. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80000. return cubeMapData;
  80001. };
  80002. /**
  80003. * Returns the pixels data extracted from an RGBE texture.
  80004. * This pixels will be stored left to right up to down in the R G B order in one array.
  80005. *
  80006. * More information on this format are available here:
  80007. * https://en.wikipedia.org/wiki/RGBE_image_format
  80008. *
  80009. * @param uint8array The binary file stored in an array buffer.
  80010. * @param hdrInfo The header information of the file.
  80011. * @return The pixels data in RGB right to left up to down order.
  80012. */
  80013. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80014. // Keep for multi format supports.
  80015. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80016. };
  80017. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80018. var num_scanlines = hdrInfo.height;
  80019. var scanline_width = hdrInfo.width;
  80020. var a, b, c, d, count;
  80021. var dataIndex = hdrInfo.dataPosition;
  80022. var index = 0, endIndex = 0, i = 0;
  80023. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80024. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80025. // 3 channels of 4 bytes per pixel in float.
  80026. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80027. var resultArray = new Float32Array(resultBuffer);
  80028. // read in each successive scanline
  80029. while (num_scanlines > 0) {
  80030. a = uint8array[dataIndex++];
  80031. b = uint8array[dataIndex++];
  80032. c = uint8array[dataIndex++];
  80033. d = uint8array[dataIndex++];
  80034. if (a != 2 || b != 2 || (c & 0x80)) {
  80035. // this file is not run length encoded
  80036. throw "HDR Bad header format, not RLE";
  80037. }
  80038. if (((c << 8) | d) != scanline_width) {
  80039. throw "HDR Bad header format, wrong scan line width";
  80040. }
  80041. index = 0;
  80042. // read each of the four channels for the scanline into the buffer
  80043. for (i = 0; i < 4; i++) {
  80044. endIndex = (i + 1) * scanline_width;
  80045. while (index < endIndex) {
  80046. a = uint8array[dataIndex++];
  80047. b = uint8array[dataIndex++];
  80048. if (a > 128) {
  80049. // a run of the same value
  80050. count = a - 128;
  80051. if ((count == 0) || (count > endIndex - index)) {
  80052. throw "HDR Bad Format, bad scanline data (run)";
  80053. }
  80054. while (count-- > 0) {
  80055. scanLineArray[index++] = b;
  80056. }
  80057. }
  80058. else {
  80059. // a non-run
  80060. count = a;
  80061. if ((count == 0) || (count > endIndex - index)) {
  80062. throw "HDR Bad Format, bad scanline data (non-run)";
  80063. }
  80064. scanLineArray[index++] = b;
  80065. if (--count > 0) {
  80066. for (var j = 0; j < count; j++) {
  80067. scanLineArray[index++] = uint8array[dataIndex++];
  80068. }
  80069. }
  80070. }
  80071. }
  80072. }
  80073. // now convert data from buffer into floats
  80074. for (i = 0; i < scanline_width; i++) {
  80075. a = scanLineArray[i];
  80076. b = scanLineArray[i + scanline_width];
  80077. c = scanLineArray[i + 2 * scanline_width];
  80078. d = scanLineArray[i + 3 * scanline_width];
  80079. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80080. }
  80081. num_scanlines--;
  80082. }
  80083. return resultArray;
  80084. };
  80085. return HDRTools;
  80086. }());
  80087. BABYLON.HDRTools = HDRTools;
  80088. })(BABYLON || (BABYLON = {}));
  80089. //# sourceMappingURL=babylon.hdr.js.map
  80090. var BABYLON;
  80091. (function (BABYLON) {
  80092. /**
  80093. * This represents a texture coming from an HDR input.
  80094. *
  80095. * The only supported format is currently panorama picture stored in RGBE format.
  80096. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80097. */
  80098. var HDRCubeTexture = /** @class */ (function (_super) {
  80099. __extends(HDRCubeTexture, _super);
  80100. /**
  80101. * Instantiates an HDRTexture from the following parameters.
  80102. *
  80103. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80104. * @param scene The scene the texture will be used in
  80105. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80106. * @param noMipmap Forces to not generate the mipmap if true
  80107. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80108. * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  80109. * @param reserved Reserved flag for internal use.
  80110. */
  80111. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80112. if (noMipmap === void 0) { noMipmap = false; }
  80113. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80114. if (gammaSpace === void 0) { gammaSpace = false; }
  80115. if (reserved === void 0) { reserved = false; }
  80116. if (onLoad === void 0) { onLoad = null; }
  80117. if (onError === void 0) { onError = null; }
  80118. var _this = _super.call(this, scene) || this;
  80119. _this._generateHarmonics = true;
  80120. _this._onLoad = null;
  80121. _this._onError = null;
  80122. /**
  80123. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80124. */
  80125. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80126. _this._isBlocking = true;
  80127. _this._rotationY = 0;
  80128. /**
  80129. * Gets or sets the center of the bounding box associated with the cube texture
  80130. * It must define where the camera used to render the texture was set
  80131. */
  80132. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80133. if (!url) {
  80134. return _this;
  80135. }
  80136. _this.name = url;
  80137. _this.url = url;
  80138. _this.hasAlpha = false;
  80139. _this.isCube = true;
  80140. _this._textureMatrix = BABYLON.Matrix.Identity();
  80141. _this._onLoad = onLoad;
  80142. _this._onError = onError;
  80143. _this.gammaSpace = gammaSpace;
  80144. _this._noMipmap = noMipmap;
  80145. _this._size = size;
  80146. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80147. if (!_this._texture) {
  80148. if (!scene.useDelayedTextureLoading) {
  80149. _this.loadTexture();
  80150. }
  80151. else {
  80152. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80153. }
  80154. }
  80155. return _this;
  80156. }
  80157. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80158. /**
  80159. * Gets wether or not the texture is blocking during loading.
  80160. */
  80161. get: function () {
  80162. return this._isBlocking;
  80163. },
  80164. /**
  80165. * Sets wether or not the texture is blocking during loading.
  80166. */
  80167. set: function (value) {
  80168. this._isBlocking = value;
  80169. },
  80170. enumerable: true,
  80171. configurable: true
  80172. });
  80173. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80174. /**
  80175. * Gets texture matrix rotation angle around Y axis radians.
  80176. */
  80177. get: function () {
  80178. return this._rotationY;
  80179. },
  80180. /**
  80181. * Sets texture matrix rotation angle around Y axis in radians.
  80182. */
  80183. set: function (value) {
  80184. this._rotationY = value;
  80185. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80186. },
  80187. enumerable: true,
  80188. configurable: true
  80189. });
  80190. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80191. get: function () {
  80192. return this._boundingBoxSize;
  80193. },
  80194. /**
  80195. * Gets or sets the size of the bounding box associated with the cube texture
  80196. * When defined, the cubemap will switch to local mode
  80197. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80198. * @example https://www.babylonjs-playground.com/#RNASML
  80199. */
  80200. set: function (value) {
  80201. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80202. return;
  80203. }
  80204. this._boundingBoxSize = value;
  80205. var scene = this.getScene();
  80206. if (scene) {
  80207. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80208. }
  80209. },
  80210. enumerable: true,
  80211. configurable: true
  80212. });
  80213. /**
  80214. * Occurs when the file is raw .hdr file.
  80215. */
  80216. HDRCubeTexture.prototype.loadTexture = function () {
  80217. var _this = this;
  80218. var callback = function (buffer) {
  80219. var scene = _this.getScene();
  80220. if (!scene) {
  80221. return null;
  80222. }
  80223. // Extract the raw linear data.
  80224. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80225. // Generate harmonics if needed.
  80226. if (_this._generateHarmonics) {
  80227. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80228. _this.sphericalPolynomial = sphericalPolynomial;
  80229. }
  80230. var results = [];
  80231. var byteArray = null;
  80232. // Push each faces.
  80233. for (var j = 0; j < 6; j++) {
  80234. // Create uintarray fallback.
  80235. if (!scene.getEngine().getCaps().textureFloat) {
  80236. // 3 channels of 1 bytes per pixel in bytes.
  80237. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80238. byteArray = new Uint8Array(byteBuffer);
  80239. }
  80240. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80241. // If special cases.
  80242. if (_this.gammaSpace || byteArray) {
  80243. for (var i = 0; i < _this._size * _this._size; i++) {
  80244. // Put in gamma space if requested.
  80245. if (_this.gammaSpace) {
  80246. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80247. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80248. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80249. }
  80250. // Convert to int texture for fallback.
  80251. if (byteArray) {
  80252. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80253. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80254. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80255. // May use luminance instead if the result is not accurate.
  80256. var max = Math.max(Math.max(r, g), b);
  80257. if (max > 255) {
  80258. var scale = 255 / max;
  80259. r *= scale;
  80260. g *= scale;
  80261. b *= scale;
  80262. }
  80263. byteArray[(i * 3) + 0] = r;
  80264. byteArray[(i * 3) + 1] = g;
  80265. byteArray[(i * 3) + 2] = b;
  80266. }
  80267. }
  80268. }
  80269. if (byteArray) {
  80270. results.push(byteArray);
  80271. }
  80272. else {
  80273. results.push(dataFace);
  80274. }
  80275. }
  80276. return results;
  80277. };
  80278. var scene = this.getScene();
  80279. if (scene) {
  80280. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  80281. }
  80282. };
  80283. HDRCubeTexture.prototype.clone = function () {
  80284. var scene = this.getScene();
  80285. if (!scene) {
  80286. return this;
  80287. }
  80288. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80289. // Base texture
  80290. newTexture.level = this.level;
  80291. newTexture.wrapU = this.wrapU;
  80292. newTexture.wrapV = this.wrapV;
  80293. newTexture.coordinatesIndex = this.coordinatesIndex;
  80294. newTexture.coordinatesMode = this.coordinatesMode;
  80295. return newTexture;
  80296. };
  80297. // Methods
  80298. HDRCubeTexture.prototype.delayLoad = function () {
  80299. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80300. return;
  80301. }
  80302. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80303. this._texture = this._getFromCache(this.url, this._noMipmap);
  80304. if (!this._texture) {
  80305. this.loadTexture();
  80306. }
  80307. };
  80308. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80309. return this._textureMatrix;
  80310. };
  80311. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80312. this._textureMatrix = value;
  80313. };
  80314. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80315. var texture = null;
  80316. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80317. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80318. texture.name = parsedTexture.name;
  80319. texture.hasAlpha = parsedTexture.hasAlpha;
  80320. texture.level = parsedTexture.level;
  80321. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80322. texture.isBlocking = parsedTexture.isBlocking;
  80323. }
  80324. if (texture) {
  80325. if (parsedTexture.boundingBoxPosition) {
  80326. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80327. }
  80328. if (parsedTexture.boundingBoxSize) {
  80329. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80330. }
  80331. if (parsedTexture.rotationY) {
  80332. texture.rotationY = parsedTexture.rotationY;
  80333. }
  80334. }
  80335. return texture;
  80336. };
  80337. HDRCubeTexture.prototype.serialize = function () {
  80338. if (!this.name) {
  80339. return null;
  80340. }
  80341. var serializationObject = {};
  80342. serializationObject.name = this.name;
  80343. serializationObject.hasAlpha = this.hasAlpha;
  80344. serializationObject.isCube = true;
  80345. serializationObject.level = this.level;
  80346. serializationObject.size = this._size;
  80347. serializationObject.coordinatesMode = this.coordinatesMode;
  80348. serializationObject.useInGammaSpace = this.gammaSpace;
  80349. serializationObject.generateHarmonics = this._generateHarmonics;
  80350. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80351. serializationObject.noMipmap = this._noMipmap;
  80352. serializationObject.isBlocking = this._isBlocking;
  80353. serializationObject.rotationY = this._rotationY;
  80354. return serializationObject;
  80355. };
  80356. HDRCubeTexture._facesMapping = [
  80357. "right",
  80358. "left",
  80359. "up",
  80360. "down",
  80361. "front",
  80362. "back"
  80363. ];
  80364. return HDRCubeTexture;
  80365. }(BABYLON.BaseTexture));
  80366. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80367. })(BABYLON || (BABYLON = {}));
  80368. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80369. var BABYLON;
  80370. (function (BABYLON) {
  80371. var IndexedVector2 = /** @class */ (function (_super) {
  80372. __extends(IndexedVector2, _super);
  80373. function IndexedVector2(original, index) {
  80374. var _this = _super.call(this, original.x, original.y) || this;
  80375. _this.index = index;
  80376. return _this;
  80377. }
  80378. return IndexedVector2;
  80379. }(BABYLON.Vector2));
  80380. var PolygonPoints = /** @class */ (function () {
  80381. function PolygonPoints() {
  80382. this.elements = new Array();
  80383. }
  80384. PolygonPoints.prototype.add = function (originalPoints) {
  80385. var _this = this;
  80386. var result = new Array();
  80387. originalPoints.forEach(function (point) {
  80388. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80389. var newPoint = new IndexedVector2(point, _this.elements.length);
  80390. result.push(newPoint);
  80391. _this.elements.push(newPoint);
  80392. }
  80393. });
  80394. return result;
  80395. };
  80396. PolygonPoints.prototype.computeBounds = function () {
  80397. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80398. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80399. this.elements.forEach(function (point) {
  80400. // x
  80401. if (point.x < lmin.x) {
  80402. lmin.x = point.x;
  80403. }
  80404. else if (point.x > lmax.x) {
  80405. lmax.x = point.x;
  80406. }
  80407. // y
  80408. if (point.y < lmin.y) {
  80409. lmin.y = point.y;
  80410. }
  80411. else if (point.y > lmax.y) {
  80412. lmax.y = point.y;
  80413. }
  80414. });
  80415. return {
  80416. min: lmin,
  80417. max: lmax,
  80418. width: lmax.x - lmin.x,
  80419. height: lmax.y - lmin.y
  80420. };
  80421. };
  80422. return PolygonPoints;
  80423. }());
  80424. var Polygon = /** @class */ (function () {
  80425. function Polygon() {
  80426. }
  80427. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80428. return [
  80429. new BABYLON.Vector2(xmin, ymin),
  80430. new BABYLON.Vector2(xmax, ymin),
  80431. new BABYLON.Vector2(xmax, ymax),
  80432. new BABYLON.Vector2(xmin, ymax)
  80433. ];
  80434. };
  80435. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80436. if (cx === void 0) { cx = 0; }
  80437. if (cy === void 0) { cy = 0; }
  80438. if (numberOfSides === void 0) { numberOfSides = 32; }
  80439. var result = new Array();
  80440. var angle = 0;
  80441. var increment = (Math.PI * 2) / numberOfSides;
  80442. for (var i = 0; i < numberOfSides; i++) {
  80443. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80444. angle -= increment;
  80445. }
  80446. return result;
  80447. };
  80448. Polygon.Parse = function (input) {
  80449. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80450. var i, result = [];
  80451. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80452. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80453. }
  80454. return result;
  80455. };
  80456. Polygon.StartingAt = function (x, y) {
  80457. return BABYLON.Path2.StartingAt(x, y);
  80458. };
  80459. return Polygon;
  80460. }());
  80461. BABYLON.Polygon = Polygon;
  80462. var PolygonMeshBuilder = /** @class */ (function () {
  80463. function PolygonMeshBuilder(name, contours, scene) {
  80464. this._points = new PolygonPoints();
  80465. this._outlinepoints = new PolygonPoints();
  80466. this._holes = new Array();
  80467. this._epoints = new Array();
  80468. this._eholes = new Array();
  80469. this._name = name;
  80470. this._scene = scene;
  80471. var points;
  80472. if (contours instanceof BABYLON.Path2) {
  80473. points = contours.getPoints();
  80474. }
  80475. else {
  80476. points = contours;
  80477. }
  80478. this._addToepoint(points);
  80479. this._points.add(points);
  80480. this._outlinepoints.add(points);
  80481. if (typeof earcut === 'undefined') {
  80482. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80483. }
  80484. }
  80485. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80486. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80487. var p = points_1[_i];
  80488. this._epoints.push(p.x, p.y);
  80489. }
  80490. };
  80491. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80492. this._points.add(hole);
  80493. var holepoints = new PolygonPoints();
  80494. holepoints.add(hole);
  80495. this._holes.push(holepoints);
  80496. this._eholes.push(this._epoints.length / 2);
  80497. this._addToepoint(hole);
  80498. return this;
  80499. };
  80500. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80501. var _this = this;
  80502. if (updatable === void 0) { updatable = false; }
  80503. if (depth === void 0) { depth = 0; }
  80504. var result = new BABYLON.Mesh(this._name, this._scene);
  80505. var normals = new Array();
  80506. var positions = new Array();
  80507. var uvs = new Array();
  80508. var bounds = this._points.computeBounds();
  80509. this._points.elements.forEach(function (p) {
  80510. normals.push(0, 1.0, 0);
  80511. positions.push(p.x, 0, p.y);
  80512. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80513. });
  80514. var indices = new Array();
  80515. var res = earcut(this._epoints, this._eholes, 2);
  80516. for (var i = 0; i < res.length; i++) {
  80517. indices.push(res[i]);
  80518. }
  80519. if (depth > 0) {
  80520. var positionscount = (positions.length / 3); //get the current pointcount
  80521. this._points.elements.forEach(function (p) {
  80522. normals.push(0, -1.0, 0);
  80523. positions.push(p.x, -depth, p.y);
  80524. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80525. });
  80526. var totalCount = indices.length;
  80527. for (var i = 0; i < totalCount; i += 3) {
  80528. var i0 = indices[i + 0];
  80529. var i1 = indices[i + 1];
  80530. var i2 = indices[i + 2];
  80531. indices.push(i2 + positionscount);
  80532. indices.push(i1 + positionscount);
  80533. indices.push(i0 + positionscount);
  80534. }
  80535. //Add the sides
  80536. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80537. this._holes.forEach(function (hole) {
  80538. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80539. });
  80540. }
  80541. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80542. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80543. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80544. result.setIndices(indices);
  80545. return result;
  80546. };
  80547. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80548. var StartIndex = positions.length / 3;
  80549. var ulength = 0;
  80550. for (var i = 0; i < points.elements.length; i++) {
  80551. var p = points.elements[i];
  80552. var p1;
  80553. if ((i + 1) > points.elements.length - 1) {
  80554. p1 = points.elements[0];
  80555. }
  80556. else {
  80557. p1 = points.elements[i + 1];
  80558. }
  80559. positions.push(p.x, 0, p.y);
  80560. positions.push(p.x, -depth, p.y);
  80561. positions.push(p1.x, 0, p1.y);
  80562. positions.push(p1.x, -depth, p1.y);
  80563. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80564. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80565. var v3 = v2.subtract(v1);
  80566. var v4 = new BABYLON.Vector3(0, 1, 0);
  80567. var vn = BABYLON.Vector3.Cross(v3, v4);
  80568. vn = vn.normalize();
  80569. uvs.push(ulength / bounds.width, 0);
  80570. uvs.push(ulength / bounds.width, 1);
  80571. ulength += v3.length();
  80572. uvs.push((ulength / bounds.width), 0);
  80573. uvs.push((ulength / bounds.width), 1);
  80574. if (!flip) {
  80575. normals.push(-vn.x, -vn.y, -vn.z);
  80576. normals.push(-vn.x, -vn.y, -vn.z);
  80577. normals.push(-vn.x, -vn.y, -vn.z);
  80578. normals.push(-vn.x, -vn.y, -vn.z);
  80579. indices.push(StartIndex);
  80580. indices.push(StartIndex + 1);
  80581. indices.push(StartIndex + 2);
  80582. indices.push(StartIndex + 1);
  80583. indices.push(StartIndex + 3);
  80584. indices.push(StartIndex + 2);
  80585. }
  80586. else {
  80587. normals.push(vn.x, vn.y, vn.z);
  80588. normals.push(vn.x, vn.y, vn.z);
  80589. normals.push(vn.x, vn.y, vn.z);
  80590. normals.push(vn.x, vn.y, vn.z);
  80591. indices.push(StartIndex);
  80592. indices.push(StartIndex + 2);
  80593. indices.push(StartIndex + 1);
  80594. indices.push(StartIndex + 1);
  80595. indices.push(StartIndex + 2);
  80596. indices.push(StartIndex + 3);
  80597. }
  80598. StartIndex += 4;
  80599. }
  80600. ;
  80601. };
  80602. return PolygonMeshBuilder;
  80603. }());
  80604. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80605. })(BABYLON || (BABYLON = {}));
  80606. //# sourceMappingURL=babylon.polygonMesh.js.map
  80607. var BABYLON;
  80608. (function (BABYLON) {
  80609. // Unique ID when we import meshes from Babylon to CSG
  80610. var currentCSGMeshId = 0;
  80611. // # class Vertex
  80612. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80613. // one to provide additional features like texture coordinates and vertex
  80614. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80615. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80616. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80617. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80618. // is not used anywhere else.
  80619. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80620. var Vertex = /** @class */ (function () {
  80621. function Vertex(pos, normal, uv) {
  80622. this.pos = pos;
  80623. this.normal = normal;
  80624. this.uv = uv;
  80625. }
  80626. Vertex.prototype.clone = function () {
  80627. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80628. };
  80629. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80630. // orientation of a polygon is flipped.
  80631. Vertex.prototype.flip = function () {
  80632. this.normal = this.normal.scale(-1);
  80633. };
  80634. // Create a new vertex between this vertex and `other` by linearly
  80635. // interpolating all properties using a parameter of `t`. Subclasses should
  80636. // override this to interpolate additional properties.
  80637. Vertex.prototype.interpolate = function (other, t) {
  80638. 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));
  80639. };
  80640. return Vertex;
  80641. }());
  80642. // # class Plane
  80643. // Represents a plane in 3D space.
  80644. var Plane = /** @class */ (function () {
  80645. function Plane(normal, w) {
  80646. this.normal = normal;
  80647. this.w = w;
  80648. }
  80649. Plane.FromPoints = function (a, b, c) {
  80650. var v0 = c.subtract(a);
  80651. var v1 = b.subtract(a);
  80652. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80653. return null;
  80654. }
  80655. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80656. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80657. };
  80658. Plane.prototype.clone = function () {
  80659. return new Plane(this.normal.clone(), this.w);
  80660. };
  80661. Plane.prototype.flip = function () {
  80662. this.normal.scaleInPlace(-1);
  80663. this.w = -this.w;
  80664. };
  80665. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80666. // fragments in the appropriate lists. Coplanar polygons go into either
  80667. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80668. // respect to this plane. Polygons in front or in back of this plane go into
  80669. // either `front` or `back`.
  80670. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80671. var COPLANAR = 0;
  80672. var FRONT = 1;
  80673. var BACK = 2;
  80674. var SPANNING = 3;
  80675. // Classify each point as well as the entire polygon into one of the above
  80676. // four classes.
  80677. var polygonType = 0;
  80678. var types = [];
  80679. var i;
  80680. var t;
  80681. for (i = 0; i < polygon.vertices.length; i++) {
  80682. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80683. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80684. polygonType |= type;
  80685. types.push(type);
  80686. }
  80687. // Put the polygon in the correct list, splitting it when necessary.
  80688. switch (polygonType) {
  80689. case COPLANAR:
  80690. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80691. break;
  80692. case FRONT:
  80693. front.push(polygon);
  80694. break;
  80695. case BACK:
  80696. back.push(polygon);
  80697. break;
  80698. case SPANNING:
  80699. var f = [], b = [];
  80700. for (i = 0; i < polygon.vertices.length; i++) {
  80701. var j = (i + 1) % polygon.vertices.length;
  80702. var ti = types[i], tj = types[j];
  80703. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80704. if (ti !== BACK)
  80705. f.push(vi);
  80706. if (ti !== FRONT)
  80707. b.push(ti !== BACK ? vi.clone() : vi);
  80708. if ((ti | tj) === SPANNING) {
  80709. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80710. var v = vi.interpolate(vj, t);
  80711. f.push(v);
  80712. b.push(v.clone());
  80713. }
  80714. }
  80715. var poly;
  80716. if (f.length >= 3) {
  80717. poly = new Polygon(f, polygon.shared);
  80718. if (poly.plane)
  80719. front.push(poly);
  80720. }
  80721. if (b.length >= 3) {
  80722. poly = new Polygon(b, polygon.shared);
  80723. if (poly.plane)
  80724. back.push(poly);
  80725. }
  80726. break;
  80727. }
  80728. };
  80729. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80730. // point is on the plane.
  80731. Plane.EPSILON = 1e-5;
  80732. return Plane;
  80733. }());
  80734. // # class Polygon
  80735. // Represents a convex polygon. The vertices used to initialize a polygon must
  80736. // be coplanar and form a convex loop.
  80737. //
  80738. // Each convex polygon has a `shared` property, which is shared between all
  80739. // polygons that are clones of each other or were split from the same polygon.
  80740. // This can be used to define per-polygon properties (such as surface color).
  80741. var Polygon = /** @class */ (function () {
  80742. function Polygon(vertices, shared) {
  80743. this.vertices = vertices;
  80744. this.shared = shared;
  80745. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80746. }
  80747. Polygon.prototype.clone = function () {
  80748. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80749. return new Polygon(vertices, this.shared);
  80750. };
  80751. Polygon.prototype.flip = function () {
  80752. this.vertices.reverse().map(function (v) { v.flip(); });
  80753. this.plane.flip();
  80754. };
  80755. return Polygon;
  80756. }());
  80757. // # class Node
  80758. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80759. // by picking a polygon to split along. That polygon (and all other coplanar
  80760. // polygons) are added directly to that node and the other polygons are added to
  80761. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80762. // no distinction between internal and leaf nodes.
  80763. var Node = /** @class */ (function () {
  80764. function Node(polygons) {
  80765. this.plane = null;
  80766. this.front = null;
  80767. this.back = null;
  80768. this.polygons = new Array();
  80769. if (polygons) {
  80770. this.build(polygons);
  80771. }
  80772. }
  80773. Node.prototype.clone = function () {
  80774. var node = new Node();
  80775. node.plane = this.plane && this.plane.clone();
  80776. node.front = this.front && this.front.clone();
  80777. node.back = this.back && this.back.clone();
  80778. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80779. return node;
  80780. };
  80781. // Convert solid space to empty space and empty space to solid space.
  80782. Node.prototype.invert = function () {
  80783. for (var i = 0; i < this.polygons.length; i++) {
  80784. this.polygons[i].flip();
  80785. }
  80786. if (this.plane) {
  80787. this.plane.flip();
  80788. }
  80789. if (this.front) {
  80790. this.front.invert();
  80791. }
  80792. if (this.back) {
  80793. this.back.invert();
  80794. }
  80795. var temp = this.front;
  80796. this.front = this.back;
  80797. this.back = temp;
  80798. };
  80799. // Recursively remove all polygons in `polygons` that are inside this BSP
  80800. // tree.
  80801. Node.prototype.clipPolygons = function (polygons) {
  80802. if (!this.plane)
  80803. return polygons.slice();
  80804. var front = new Array(), back = new Array();
  80805. for (var i = 0; i < polygons.length; i++) {
  80806. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80807. }
  80808. if (this.front) {
  80809. front = this.front.clipPolygons(front);
  80810. }
  80811. if (this.back) {
  80812. back = this.back.clipPolygons(back);
  80813. }
  80814. else {
  80815. back = [];
  80816. }
  80817. return front.concat(back);
  80818. };
  80819. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80820. // `bsp`.
  80821. Node.prototype.clipTo = function (bsp) {
  80822. this.polygons = bsp.clipPolygons(this.polygons);
  80823. if (this.front)
  80824. this.front.clipTo(bsp);
  80825. if (this.back)
  80826. this.back.clipTo(bsp);
  80827. };
  80828. // Return a list of all polygons in this BSP tree.
  80829. Node.prototype.allPolygons = function () {
  80830. var polygons = this.polygons.slice();
  80831. if (this.front)
  80832. polygons = polygons.concat(this.front.allPolygons());
  80833. if (this.back)
  80834. polygons = polygons.concat(this.back.allPolygons());
  80835. return polygons;
  80836. };
  80837. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80838. // new polygons are filtered down to the bottom of the tree and become new
  80839. // nodes there. Each set of polygons is partitioned using the first polygon
  80840. // (no heuristic is used to pick a good split).
  80841. Node.prototype.build = function (polygons) {
  80842. if (!polygons.length)
  80843. return;
  80844. if (!this.plane)
  80845. this.plane = polygons[0].plane.clone();
  80846. var front = new Array(), back = new Array();
  80847. for (var i = 0; i < polygons.length; i++) {
  80848. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80849. }
  80850. if (front.length) {
  80851. if (!this.front)
  80852. this.front = new Node();
  80853. this.front.build(front);
  80854. }
  80855. if (back.length) {
  80856. if (!this.back)
  80857. this.back = new Node();
  80858. this.back.build(back);
  80859. }
  80860. };
  80861. return Node;
  80862. }());
  80863. var CSG = /** @class */ (function () {
  80864. function CSG() {
  80865. this.polygons = new Array();
  80866. }
  80867. // Convert BABYLON.Mesh to BABYLON.CSG
  80868. CSG.FromMesh = function (mesh) {
  80869. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80870. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80871. if (mesh instanceof BABYLON.Mesh) {
  80872. mesh.computeWorldMatrix(true);
  80873. matrix = mesh.getWorldMatrix();
  80874. meshPosition = mesh.position.clone();
  80875. meshRotation = mesh.rotation.clone();
  80876. if (mesh.rotationQuaternion) {
  80877. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  80878. }
  80879. meshScaling = mesh.scaling.clone();
  80880. }
  80881. else {
  80882. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  80883. }
  80884. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80885. var subMeshes = mesh.subMeshes;
  80886. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  80887. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  80888. vertices = [];
  80889. for (var j = 0; j < 3; j++) {
  80890. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  80891. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  80892. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  80893. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  80894. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  80895. vertex = new Vertex(position, normal, uv);
  80896. vertices.push(vertex);
  80897. }
  80898. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  80899. // To handle the case of degenerated triangle
  80900. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  80901. if (polygon.plane)
  80902. polygons.push(polygon);
  80903. }
  80904. }
  80905. var csg = CSG.FromPolygons(polygons);
  80906. csg.matrix = matrix;
  80907. csg.position = meshPosition;
  80908. csg.rotation = meshRotation;
  80909. csg.scaling = meshScaling;
  80910. csg.rotationQuaternion = meshRotationQuaternion;
  80911. currentCSGMeshId++;
  80912. return csg;
  80913. };
  80914. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  80915. CSG.FromPolygons = function (polygons) {
  80916. var csg = new CSG();
  80917. csg.polygons = polygons;
  80918. return csg;
  80919. };
  80920. CSG.prototype.clone = function () {
  80921. var csg = new CSG();
  80922. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  80923. csg.copyTransformAttributes(this);
  80924. return csg;
  80925. };
  80926. CSG.prototype.union = function (csg) {
  80927. var a = new Node(this.clone().polygons);
  80928. var b = new Node(csg.clone().polygons);
  80929. a.clipTo(b);
  80930. b.clipTo(a);
  80931. b.invert();
  80932. b.clipTo(a);
  80933. b.invert();
  80934. a.build(b.allPolygons());
  80935. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80936. };
  80937. CSG.prototype.unionInPlace = function (csg) {
  80938. var a = new Node(this.polygons);
  80939. var b = new Node(csg.polygons);
  80940. a.clipTo(b);
  80941. b.clipTo(a);
  80942. b.invert();
  80943. b.clipTo(a);
  80944. b.invert();
  80945. a.build(b.allPolygons());
  80946. this.polygons = a.allPolygons();
  80947. };
  80948. CSG.prototype.subtract = function (csg) {
  80949. var a = new Node(this.clone().polygons);
  80950. var b = new Node(csg.clone().polygons);
  80951. a.invert();
  80952. a.clipTo(b);
  80953. b.clipTo(a);
  80954. b.invert();
  80955. b.clipTo(a);
  80956. b.invert();
  80957. a.build(b.allPolygons());
  80958. a.invert();
  80959. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80960. };
  80961. CSG.prototype.subtractInPlace = function (csg) {
  80962. var a = new Node(this.polygons);
  80963. var b = new Node(csg.polygons);
  80964. a.invert();
  80965. a.clipTo(b);
  80966. b.clipTo(a);
  80967. b.invert();
  80968. b.clipTo(a);
  80969. b.invert();
  80970. a.build(b.allPolygons());
  80971. a.invert();
  80972. this.polygons = a.allPolygons();
  80973. };
  80974. CSG.prototype.intersect = function (csg) {
  80975. var a = new Node(this.clone().polygons);
  80976. var b = new Node(csg.clone().polygons);
  80977. a.invert();
  80978. b.clipTo(a);
  80979. b.invert();
  80980. a.clipTo(b);
  80981. b.clipTo(a);
  80982. a.build(b.allPolygons());
  80983. a.invert();
  80984. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80985. };
  80986. CSG.prototype.intersectInPlace = function (csg) {
  80987. var a = new Node(this.polygons);
  80988. var b = new Node(csg.polygons);
  80989. a.invert();
  80990. b.clipTo(a);
  80991. b.invert();
  80992. a.clipTo(b);
  80993. b.clipTo(a);
  80994. a.build(b.allPolygons());
  80995. a.invert();
  80996. this.polygons = a.allPolygons();
  80997. };
  80998. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  80999. // not modified.
  81000. CSG.prototype.inverse = function () {
  81001. var csg = this.clone();
  81002. csg.inverseInPlace();
  81003. return csg;
  81004. };
  81005. CSG.prototype.inverseInPlace = function () {
  81006. this.polygons.map(function (p) { p.flip(); });
  81007. };
  81008. // This is used to keep meshes transformations so they can be restored
  81009. // when we build back a Babylon Mesh
  81010. // NB : All CSG operations are performed in world coordinates
  81011. CSG.prototype.copyTransformAttributes = function (csg) {
  81012. this.matrix = csg.matrix;
  81013. this.position = csg.position;
  81014. this.rotation = csg.rotation;
  81015. this.scaling = csg.scaling;
  81016. this.rotationQuaternion = csg.rotationQuaternion;
  81017. return this;
  81018. };
  81019. // Build Raw mesh from CSG
  81020. // Coordinates here are in world space
  81021. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81022. var matrix = this.matrix.clone();
  81023. matrix.invert();
  81024. 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;
  81025. if (keepSubMeshes) {
  81026. // Sort Polygons, since subMeshes are indices range
  81027. polygons.sort(function (a, b) {
  81028. if (a.shared.meshId === b.shared.meshId) {
  81029. return a.shared.subMeshId - b.shared.subMeshId;
  81030. }
  81031. else {
  81032. return a.shared.meshId - b.shared.meshId;
  81033. }
  81034. });
  81035. }
  81036. for (var i = 0, il = polygons.length; i < il; i++) {
  81037. polygon = polygons[i];
  81038. // Building SubMeshes
  81039. if (!subMesh_dict[polygon.shared.meshId]) {
  81040. subMesh_dict[polygon.shared.meshId] = {};
  81041. }
  81042. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81043. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81044. indexStart: +Infinity,
  81045. indexEnd: -Infinity,
  81046. materialIndex: polygon.shared.materialIndex
  81047. };
  81048. }
  81049. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81050. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81051. polygonIndices[0] = 0;
  81052. polygonIndices[1] = j - 1;
  81053. polygonIndices[2] = j;
  81054. for (var k = 0; k < 3; k++) {
  81055. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81056. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81057. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81058. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81059. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81060. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81061. // Check if 2 points can be merged
  81062. if (!(typeof vertex_idx !== 'undefined' &&
  81063. normals[vertex_idx * 3] === localNormal.x &&
  81064. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81065. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81066. uvs[vertex_idx * 2] === uv.x &&
  81067. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81068. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81069. uvs.push(uv.x, uv.y);
  81070. normals.push(normal.x, normal.y, normal.z);
  81071. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81072. }
  81073. indices.push(vertex_idx);
  81074. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81075. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81076. currentIndex++;
  81077. }
  81078. }
  81079. }
  81080. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81081. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81082. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81083. mesh.setIndices(indices, null);
  81084. if (keepSubMeshes) {
  81085. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81086. var materialIndexOffset = 0, materialMaxIndex;
  81087. mesh.subMeshes = new Array();
  81088. for (var m in subMesh_dict) {
  81089. materialMaxIndex = -1;
  81090. for (var sm in subMesh_dict[m]) {
  81091. subMesh_obj = subMesh_dict[m][sm];
  81092. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81093. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81094. }
  81095. materialIndexOffset += ++materialMaxIndex;
  81096. }
  81097. }
  81098. return mesh;
  81099. };
  81100. // Build Mesh from CSG taking material and transforms into account
  81101. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81102. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81103. mesh.material = material;
  81104. mesh.position.copyFrom(this.position);
  81105. mesh.rotation.copyFrom(this.rotation);
  81106. if (this.rotationQuaternion) {
  81107. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81108. }
  81109. mesh.scaling.copyFrom(this.scaling);
  81110. mesh.computeWorldMatrix(true);
  81111. return mesh;
  81112. };
  81113. return CSG;
  81114. }());
  81115. BABYLON.CSG = CSG;
  81116. })(BABYLON || (BABYLON = {}));
  81117. //# sourceMappingURL=babylon.csg.js.map
  81118. var BABYLON;
  81119. (function (BABYLON) {
  81120. var LensFlare = /** @class */ (function () {
  81121. function LensFlare(size, position, color, imgUrl, system) {
  81122. this.size = size;
  81123. this.position = position;
  81124. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81125. this.color = color || new BABYLON.Color3(1, 1, 1);
  81126. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81127. this._system = system;
  81128. system.lensFlares.push(this);
  81129. }
  81130. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81131. return new LensFlare(size, position, color, imgUrl, system);
  81132. };
  81133. LensFlare.prototype.dispose = function () {
  81134. if (this.texture) {
  81135. this.texture.dispose();
  81136. }
  81137. // Remove from scene
  81138. var index = this._system.lensFlares.indexOf(this);
  81139. this._system.lensFlares.splice(index, 1);
  81140. };
  81141. ;
  81142. return LensFlare;
  81143. }());
  81144. BABYLON.LensFlare = LensFlare;
  81145. })(BABYLON || (BABYLON = {}));
  81146. //# sourceMappingURL=babylon.lensFlare.js.map
  81147. var BABYLON;
  81148. (function (BABYLON) {
  81149. var LensFlareSystem = /** @class */ (function () {
  81150. function LensFlareSystem(name, emitter, scene) {
  81151. this.name = name;
  81152. this.lensFlares = new Array();
  81153. this.borderLimit = 300;
  81154. this.viewportBorder = 0;
  81155. this.layerMask = 0x0FFFFFFF;
  81156. this._vertexBuffers = {};
  81157. this._isEnabled = true;
  81158. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81159. this._emitter = emitter;
  81160. this.id = name;
  81161. scene.lensFlareSystems.push(this);
  81162. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81163. var engine = scene.getEngine();
  81164. // VBO
  81165. var vertices = [];
  81166. vertices.push(1, 1);
  81167. vertices.push(-1, 1);
  81168. vertices.push(-1, -1);
  81169. vertices.push(1, -1);
  81170. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81171. // Indices
  81172. var indices = [];
  81173. indices.push(0);
  81174. indices.push(1);
  81175. indices.push(2);
  81176. indices.push(0);
  81177. indices.push(2);
  81178. indices.push(3);
  81179. this._indexBuffer = engine.createIndexBuffer(indices);
  81180. // Effects
  81181. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81182. }
  81183. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81184. get: function () {
  81185. return this._isEnabled;
  81186. },
  81187. set: function (value) {
  81188. this._isEnabled = value;
  81189. },
  81190. enumerable: true,
  81191. configurable: true
  81192. });
  81193. LensFlareSystem.prototype.getScene = function () {
  81194. return this._scene;
  81195. };
  81196. LensFlareSystem.prototype.getEmitter = function () {
  81197. return this._emitter;
  81198. };
  81199. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81200. this._emitter = newEmitter;
  81201. };
  81202. LensFlareSystem.prototype.getEmitterPosition = function () {
  81203. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81204. };
  81205. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81206. var position = this.getEmitterPosition();
  81207. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81208. this._positionX = position.x;
  81209. this._positionY = position.y;
  81210. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81211. if (this.viewportBorder > 0) {
  81212. globalViewport.x -= this.viewportBorder;
  81213. globalViewport.y -= this.viewportBorder;
  81214. globalViewport.width += this.viewportBorder * 2;
  81215. globalViewport.height += this.viewportBorder * 2;
  81216. position.x += this.viewportBorder;
  81217. position.y += this.viewportBorder;
  81218. this._positionX += this.viewportBorder;
  81219. this._positionY += this.viewportBorder;
  81220. }
  81221. if (position.z > 0) {
  81222. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81223. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81224. return true;
  81225. }
  81226. return true;
  81227. }
  81228. return false;
  81229. };
  81230. LensFlareSystem.prototype._isVisible = function () {
  81231. if (!this._isEnabled || !this._scene.activeCamera) {
  81232. return false;
  81233. }
  81234. var emitterPosition = this.getEmitterPosition();
  81235. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81236. var distance = direction.length();
  81237. direction.normalize();
  81238. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81239. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81240. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81241. };
  81242. LensFlareSystem.prototype.render = function () {
  81243. if (!this._effect.isReady() || !this._scene.activeCamera)
  81244. return false;
  81245. var engine = this._scene.getEngine();
  81246. var viewport = this._scene.activeCamera.viewport;
  81247. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81248. // Position
  81249. if (!this.computeEffectivePosition(globalViewport)) {
  81250. return false;
  81251. }
  81252. // Visibility
  81253. if (!this._isVisible()) {
  81254. return false;
  81255. }
  81256. // Intensity
  81257. var awayX;
  81258. var awayY;
  81259. if (this._positionX < this.borderLimit + globalViewport.x) {
  81260. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81261. }
  81262. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81263. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81264. }
  81265. else {
  81266. awayX = 0;
  81267. }
  81268. if (this._positionY < this.borderLimit + globalViewport.y) {
  81269. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81270. }
  81271. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81272. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81273. }
  81274. else {
  81275. awayY = 0;
  81276. }
  81277. var away = (awayX > awayY) ? awayX : awayY;
  81278. away -= this.viewportBorder;
  81279. if (away > this.borderLimit) {
  81280. away = this.borderLimit;
  81281. }
  81282. var intensity = 1.0 - (away / this.borderLimit);
  81283. if (intensity < 0) {
  81284. return false;
  81285. }
  81286. if (intensity > 1.0) {
  81287. intensity = 1.0;
  81288. }
  81289. if (this.viewportBorder > 0) {
  81290. globalViewport.x += this.viewportBorder;
  81291. globalViewport.y += this.viewportBorder;
  81292. globalViewport.width -= this.viewportBorder * 2;
  81293. globalViewport.height -= this.viewportBorder * 2;
  81294. this._positionX -= this.viewportBorder;
  81295. this._positionY -= this.viewportBorder;
  81296. }
  81297. // Position
  81298. var centerX = globalViewport.x + globalViewport.width / 2;
  81299. var centerY = globalViewport.y + globalViewport.height / 2;
  81300. var distX = centerX - this._positionX;
  81301. var distY = centerY - this._positionY;
  81302. // Effects
  81303. engine.enableEffect(this._effect);
  81304. engine.setState(false);
  81305. engine.setDepthBuffer(false);
  81306. // VBOs
  81307. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81308. // Flares
  81309. for (var index = 0; index < this.lensFlares.length; index++) {
  81310. var flare = this.lensFlares[index];
  81311. engine.setAlphaMode(flare.alphaMode);
  81312. var x = centerX - (distX * flare.position);
  81313. var y = centerY - (distY * flare.position);
  81314. var cw = flare.size;
  81315. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81316. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81317. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81318. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81319. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81320. // Texture
  81321. this._effect.setTexture("textureSampler", flare.texture);
  81322. // Color
  81323. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81324. // Draw order
  81325. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81326. }
  81327. engine.setDepthBuffer(true);
  81328. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81329. return true;
  81330. };
  81331. LensFlareSystem.prototype.dispose = function () {
  81332. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81333. if (vertexBuffer) {
  81334. vertexBuffer.dispose();
  81335. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81336. }
  81337. if (this._indexBuffer) {
  81338. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81339. this._indexBuffer = null;
  81340. }
  81341. while (this.lensFlares.length) {
  81342. this.lensFlares[0].dispose();
  81343. }
  81344. // Remove from scene
  81345. var index = this._scene.lensFlareSystems.indexOf(this);
  81346. this._scene.lensFlareSystems.splice(index, 1);
  81347. };
  81348. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81349. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81350. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81351. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81352. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81353. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81354. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81355. var parsedFlare = parsedLensFlareSystem.flares[index];
  81356. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81357. }
  81358. return lensFlareSystem;
  81359. };
  81360. LensFlareSystem.prototype.serialize = function () {
  81361. var serializationObject = {};
  81362. serializationObject.id = this.id;
  81363. serializationObject.name = this.name;
  81364. serializationObject.emitterId = this.getEmitter().id;
  81365. serializationObject.borderLimit = this.borderLimit;
  81366. serializationObject.flares = [];
  81367. for (var index = 0; index < this.lensFlares.length; index++) {
  81368. var flare = this.lensFlares[index];
  81369. serializationObject.flares.push({
  81370. size: flare.size,
  81371. position: flare.position,
  81372. color: flare.color.asArray(),
  81373. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81374. });
  81375. }
  81376. return serializationObject;
  81377. };
  81378. return LensFlareSystem;
  81379. }());
  81380. BABYLON.LensFlareSystem = LensFlareSystem;
  81381. })(BABYLON || (BABYLON = {}));
  81382. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81383. var BABYLON;
  81384. (function (BABYLON) {
  81385. /**
  81386. * This is a holder class for the physics joint created by the physics plugin.
  81387. * It holds a set of functions to control the underlying joint.
  81388. */
  81389. var PhysicsJoint = /** @class */ (function () {
  81390. function PhysicsJoint(type, jointData) {
  81391. this.type = type;
  81392. this.jointData = jointData;
  81393. jointData.nativeParams = jointData.nativeParams || {};
  81394. }
  81395. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81396. get: function () {
  81397. return this._physicsJoint;
  81398. },
  81399. set: function (newJoint) {
  81400. if (this._physicsJoint) {
  81401. //remove from the wolrd
  81402. }
  81403. this._physicsJoint = newJoint;
  81404. },
  81405. enumerable: true,
  81406. configurable: true
  81407. });
  81408. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81409. set: function (physicsPlugin) {
  81410. this._physicsPlugin = physicsPlugin;
  81411. },
  81412. enumerable: true,
  81413. configurable: true
  81414. });
  81415. /**
  81416. * Execute a function that is physics-plugin specific.
  81417. * @param {Function} func the function that will be executed.
  81418. * It accepts two parameters: the physics world and the physics joint.
  81419. */
  81420. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81421. func(this._physicsPlugin.world, this._physicsJoint);
  81422. };
  81423. //TODO check if the native joints are the same
  81424. //Joint Types
  81425. PhysicsJoint.DistanceJoint = 0;
  81426. PhysicsJoint.HingeJoint = 1;
  81427. PhysicsJoint.BallAndSocketJoint = 2;
  81428. PhysicsJoint.WheelJoint = 3;
  81429. PhysicsJoint.SliderJoint = 4;
  81430. //OIMO
  81431. PhysicsJoint.PrismaticJoint = 5;
  81432. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81433. PhysicsJoint.UniversalJoint = 6;
  81434. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81435. //Cannon
  81436. //Similar to a Ball-Joint. Different in params
  81437. PhysicsJoint.PointToPointJoint = 8;
  81438. //Cannon only at the moment
  81439. PhysicsJoint.SpringJoint = 9;
  81440. PhysicsJoint.LockJoint = 10;
  81441. return PhysicsJoint;
  81442. }());
  81443. BABYLON.PhysicsJoint = PhysicsJoint;
  81444. /**
  81445. * A class representing a physics distance joint.
  81446. */
  81447. var DistanceJoint = /** @class */ (function (_super) {
  81448. __extends(DistanceJoint, _super);
  81449. function DistanceJoint(jointData) {
  81450. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81451. }
  81452. /**
  81453. * Update the predefined distance.
  81454. */
  81455. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81456. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81457. };
  81458. return DistanceJoint;
  81459. }(PhysicsJoint));
  81460. BABYLON.DistanceJoint = DistanceJoint;
  81461. var MotorEnabledJoint = /** @class */ (function (_super) {
  81462. __extends(MotorEnabledJoint, _super);
  81463. function MotorEnabledJoint(type, jointData) {
  81464. return _super.call(this, type, jointData) || this;
  81465. }
  81466. /**
  81467. * Set the motor values.
  81468. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81469. * @param {number} force the force to apply
  81470. * @param {number} maxForce max force for this motor.
  81471. */
  81472. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81473. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81474. };
  81475. /**
  81476. * Set the motor's limits.
  81477. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81478. */
  81479. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81480. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81481. };
  81482. return MotorEnabledJoint;
  81483. }(PhysicsJoint));
  81484. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81485. /**
  81486. * This class represents a single hinge physics joint
  81487. */
  81488. var HingeJoint = /** @class */ (function (_super) {
  81489. __extends(HingeJoint, _super);
  81490. function HingeJoint(jointData) {
  81491. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81492. }
  81493. /**
  81494. * Set the motor values.
  81495. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81496. * @param {number} force the force to apply
  81497. * @param {number} maxForce max force for this motor.
  81498. */
  81499. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81500. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81501. };
  81502. /**
  81503. * Set the motor's limits.
  81504. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81505. */
  81506. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81507. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81508. };
  81509. return HingeJoint;
  81510. }(MotorEnabledJoint));
  81511. BABYLON.HingeJoint = HingeJoint;
  81512. /**
  81513. * This class represents a dual hinge physics joint (same as wheel joint)
  81514. */
  81515. var Hinge2Joint = /** @class */ (function (_super) {
  81516. __extends(Hinge2Joint, _super);
  81517. function Hinge2Joint(jointData) {
  81518. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81519. }
  81520. /**
  81521. * Set the motor values.
  81522. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81523. * @param {number} force the force to apply
  81524. * @param {number} maxForce max force for this motor.
  81525. * @param {motorIndex} the motor's index, 0 or 1.
  81526. */
  81527. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81528. if (motorIndex === void 0) { motorIndex = 0; }
  81529. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81530. };
  81531. /**
  81532. * Set the motor limits.
  81533. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81534. * @param {number} upperLimit the upper limit
  81535. * @param {number} lowerLimit lower limit
  81536. * @param {motorIndex} the motor's index, 0 or 1.
  81537. */
  81538. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81539. if (motorIndex === void 0) { motorIndex = 0; }
  81540. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81541. };
  81542. return Hinge2Joint;
  81543. }(MotorEnabledJoint));
  81544. BABYLON.Hinge2Joint = Hinge2Joint;
  81545. })(BABYLON || (BABYLON = {}));
  81546. //# sourceMappingURL=babylon.physicsJoint.js.map
  81547. var BABYLON;
  81548. (function (BABYLON) {
  81549. var PhysicsImpostor = /** @class */ (function () {
  81550. function PhysicsImpostor(object, type, _options, _scene) {
  81551. if (_options === void 0) { _options = { mass: 0 }; }
  81552. var _this = this;
  81553. this.object = object;
  81554. this.type = type;
  81555. this._options = _options;
  81556. this._scene = _scene;
  81557. this._bodyUpdateRequired = false;
  81558. this._onBeforePhysicsStepCallbacks = new Array();
  81559. this._onAfterPhysicsStepCallbacks = new Array();
  81560. this._onPhysicsCollideCallbacks = [];
  81561. this._deltaPosition = BABYLON.Vector3.Zero();
  81562. this._isDisposed = false;
  81563. //temp variables for parent rotation calculations
  81564. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81565. this._tmpQuat = new BABYLON.Quaternion();
  81566. this._tmpQuat2 = new BABYLON.Quaternion();
  81567. /**
  81568. * this function is executed by the physics engine.
  81569. */
  81570. this.beforeStep = function () {
  81571. if (!_this._physicsEngine) {
  81572. return;
  81573. }
  81574. _this.object.translate(_this._deltaPosition, -1);
  81575. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81576. _this.object.computeWorldMatrix(false);
  81577. if (_this.object.parent && _this.object.rotationQuaternion) {
  81578. _this.getParentsRotation();
  81579. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81580. }
  81581. else {
  81582. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81583. }
  81584. if (!_this._options.disableBidirectionalTransformation) {
  81585. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81586. }
  81587. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81588. func(_this);
  81589. });
  81590. };
  81591. /**
  81592. * this function is executed by the physics engine.
  81593. */
  81594. this.afterStep = function () {
  81595. if (!_this._physicsEngine) {
  81596. return;
  81597. }
  81598. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81599. func(_this);
  81600. });
  81601. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81602. // object has now its world rotation. needs to be converted to local.
  81603. if (_this.object.parent && _this.object.rotationQuaternion) {
  81604. _this.getParentsRotation();
  81605. _this._tmpQuat.conjugateInPlace();
  81606. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81607. }
  81608. // take the position set and make it the absolute position of this object.
  81609. _this.object.setAbsolutePosition(_this.object.position);
  81610. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81611. _this.object.translate(_this._deltaPosition, 1);
  81612. };
  81613. /**
  81614. * Legacy collision detection event support
  81615. */
  81616. this.onCollideEvent = null;
  81617. //event and body object due to cannon's event-based architecture.
  81618. this.onCollide = function (e) {
  81619. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81620. return;
  81621. }
  81622. if (!_this._physicsEngine) {
  81623. return;
  81624. }
  81625. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81626. if (otherImpostor) {
  81627. // Legacy collision detection event support
  81628. if (_this.onCollideEvent) {
  81629. _this.onCollideEvent(_this, otherImpostor);
  81630. }
  81631. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81632. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81633. }).forEach(function (obj) {
  81634. obj.callback(_this, otherImpostor);
  81635. });
  81636. }
  81637. };
  81638. //sanity check!
  81639. if (!this.object) {
  81640. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81641. return;
  81642. }
  81643. //legacy support for old syntax.
  81644. if (!this._scene && object.getScene) {
  81645. this._scene = object.getScene();
  81646. }
  81647. if (!this._scene) {
  81648. return;
  81649. }
  81650. this._physicsEngine = this._scene.getPhysicsEngine();
  81651. if (!this._physicsEngine) {
  81652. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81653. }
  81654. else {
  81655. //set the object's quaternion, if not set
  81656. if (!this.object.rotationQuaternion) {
  81657. if (this.object.rotation) {
  81658. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81659. }
  81660. else {
  81661. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81662. }
  81663. }
  81664. //default options params
  81665. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81666. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81667. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81668. this._joints = [];
  81669. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81670. if (!this.object.parent || this._options.ignoreParent) {
  81671. this._init();
  81672. }
  81673. else if (this.object.parent.physicsImpostor) {
  81674. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81675. }
  81676. }
  81677. }
  81678. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81679. get: function () {
  81680. return this._isDisposed;
  81681. },
  81682. enumerable: true,
  81683. configurable: true
  81684. });
  81685. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81686. get: function () {
  81687. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81688. },
  81689. set: function (value) {
  81690. this.setMass(value);
  81691. },
  81692. enumerable: true,
  81693. configurable: true
  81694. });
  81695. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81696. get: function () {
  81697. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81698. },
  81699. set: function (value) {
  81700. if (!this._physicsEngine) {
  81701. return;
  81702. }
  81703. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81704. },
  81705. enumerable: true,
  81706. configurable: true
  81707. });
  81708. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81709. get: function () {
  81710. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81711. },
  81712. set: function (value) {
  81713. if (!this._physicsEngine) {
  81714. return;
  81715. }
  81716. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81717. },
  81718. enumerable: true,
  81719. configurable: true
  81720. });
  81721. /**
  81722. * This function will completly initialize this impostor.
  81723. * It will create a new body - but only if this mesh has no parent.
  81724. * If it has, this impostor will not be used other than to define the impostor
  81725. * of the child mesh.
  81726. */
  81727. PhysicsImpostor.prototype._init = function () {
  81728. if (!this._physicsEngine) {
  81729. return;
  81730. }
  81731. this._physicsEngine.removeImpostor(this);
  81732. this.physicsBody = null;
  81733. this._parent = this._parent || this._getPhysicsParent();
  81734. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81735. this._physicsEngine.addImpostor(this);
  81736. }
  81737. };
  81738. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81739. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81740. var parentMesh = this.object.parent;
  81741. return parentMesh.physicsImpostor;
  81742. }
  81743. return null;
  81744. };
  81745. /**
  81746. * Should a new body be generated.
  81747. */
  81748. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81749. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81750. };
  81751. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81752. this.forceUpdate();
  81753. };
  81754. /**
  81755. * Force a regeneration of this or the parent's impostor's body.
  81756. * Use under cautious - This will remove all joints already implemented.
  81757. */
  81758. PhysicsImpostor.prototype.forceUpdate = function () {
  81759. this._init();
  81760. if (this.parent && !this._options.ignoreParent) {
  81761. this.parent.forceUpdate();
  81762. }
  81763. };
  81764. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81765. /*public get mesh(): AbstractMesh {
  81766. return this._mesh;
  81767. }*/
  81768. /**
  81769. * Gets the body that holds this impostor. Either its own, or its parent.
  81770. */
  81771. get: function () {
  81772. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81773. },
  81774. /**
  81775. * Set the physics body. Used mainly by the physics engine/plugin
  81776. */
  81777. set: function (physicsBody) {
  81778. if (this._physicsBody && this._physicsEngine) {
  81779. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81780. }
  81781. this._physicsBody = physicsBody;
  81782. this.resetUpdateFlags();
  81783. },
  81784. enumerable: true,
  81785. configurable: true
  81786. });
  81787. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81788. get: function () {
  81789. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81790. },
  81791. set: function (value) {
  81792. this._parent = value;
  81793. },
  81794. enumerable: true,
  81795. configurable: true
  81796. });
  81797. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81798. this._bodyUpdateRequired = false;
  81799. };
  81800. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81801. if (this.object.getBoundingInfo) {
  81802. var q = this.object.rotationQuaternion;
  81803. //reset rotation
  81804. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81805. //calculate the world matrix with no rotation
  81806. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81807. var boundingInfo = this.object.getBoundingInfo();
  81808. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81809. //bring back the rotation
  81810. this.object.rotationQuaternion = q;
  81811. //calculate the world matrix with the new rotation
  81812. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81813. return size;
  81814. }
  81815. else {
  81816. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81817. }
  81818. };
  81819. PhysicsImpostor.prototype.getObjectCenter = function () {
  81820. if (this.object.getBoundingInfo) {
  81821. var boundingInfo = this.object.getBoundingInfo();
  81822. return boundingInfo.boundingBox.centerWorld;
  81823. }
  81824. else {
  81825. return this.object.position;
  81826. }
  81827. };
  81828. /**
  81829. * Get a specific parametes from the options parameter.
  81830. */
  81831. PhysicsImpostor.prototype.getParam = function (paramName) {
  81832. return this._options[paramName];
  81833. };
  81834. /**
  81835. * Sets a specific parameter in the options given to the physics plugin
  81836. */
  81837. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81838. this._options[paramName] = value;
  81839. this._bodyUpdateRequired = true;
  81840. };
  81841. /**
  81842. * Specifically change the body's mass option. Won't recreate the physics body object
  81843. */
  81844. PhysicsImpostor.prototype.setMass = function (mass) {
  81845. if (this.getParam("mass") !== mass) {
  81846. this.setParam("mass", mass);
  81847. }
  81848. if (this._physicsEngine) {
  81849. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81850. }
  81851. };
  81852. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81853. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81854. };
  81855. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81856. if (this._physicsEngine) {
  81857. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81858. }
  81859. };
  81860. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81861. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81862. };
  81863. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81864. if (this._physicsEngine) {
  81865. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81866. }
  81867. };
  81868. /**
  81869. * Execute a function with the physics plugin native code.
  81870. * Provide a function the will have two variables - the world object and the physics body object.
  81871. */
  81872. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81873. if (this._physicsEngine) {
  81874. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81875. }
  81876. };
  81877. /**
  81878. * Register a function that will be executed before the physics world is stepping forward.
  81879. */
  81880. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  81881. this._onBeforePhysicsStepCallbacks.push(func);
  81882. };
  81883. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  81884. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  81885. if (index > -1) {
  81886. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  81887. }
  81888. else {
  81889. BABYLON.Tools.Warn("Function to remove was not found");
  81890. }
  81891. };
  81892. /**
  81893. * Register a function that will be executed after the physics step
  81894. */
  81895. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  81896. this._onAfterPhysicsStepCallbacks.push(func);
  81897. };
  81898. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  81899. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  81900. if (index > -1) {
  81901. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  81902. }
  81903. else {
  81904. BABYLON.Tools.Warn("Function to remove was not found");
  81905. }
  81906. };
  81907. /**
  81908. * register a function that will be executed when this impostor collides against a different body.
  81909. */
  81910. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  81911. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81912. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  81913. };
  81914. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  81915. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81916. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  81917. if (index > -1) {
  81918. this._onPhysicsCollideCallbacks.splice(index, 1);
  81919. }
  81920. else {
  81921. BABYLON.Tools.Warn("Function to remove was not found");
  81922. }
  81923. };
  81924. PhysicsImpostor.prototype.getParentsRotation = function () {
  81925. var parent = this.object.parent;
  81926. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  81927. while (parent) {
  81928. if (parent.rotationQuaternion) {
  81929. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  81930. }
  81931. else {
  81932. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  81933. }
  81934. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  81935. parent = parent.parent;
  81936. }
  81937. return this._tmpQuat;
  81938. };
  81939. /**
  81940. * Apply a force
  81941. */
  81942. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  81943. if (this._physicsEngine) {
  81944. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  81945. }
  81946. return this;
  81947. };
  81948. /**
  81949. * Apply an impulse
  81950. */
  81951. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  81952. if (this._physicsEngine) {
  81953. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  81954. }
  81955. return this;
  81956. };
  81957. /**
  81958. * A help function to create a joint.
  81959. */
  81960. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  81961. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  81962. this.addJoint(otherImpostor, joint);
  81963. return this;
  81964. };
  81965. /**
  81966. * Add a joint to this impostor with a different impostor.
  81967. */
  81968. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  81969. this._joints.push({
  81970. otherImpostor: otherImpostor,
  81971. joint: joint
  81972. });
  81973. if (this._physicsEngine) {
  81974. this._physicsEngine.addJoint(this, otherImpostor, joint);
  81975. }
  81976. return this;
  81977. };
  81978. /**
  81979. * Will keep this body still, in a sleep mode.
  81980. */
  81981. PhysicsImpostor.prototype.sleep = function () {
  81982. if (this._physicsEngine) {
  81983. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  81984. }
  81985. return this;
  81986. };
  81987. /**
  81988. * Wake the body up.
  81989. */
  81990. PhysicsImpostor.prototype.wakeUp = function () {
  81991. if (this._physicsEngine) {
  81992. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  81993. }
  81994. return this;
  81995. };
  81996. PhysicsImpostor.prototype.clone = function (newObject) {
  81997. if (!newObject)
  81998. return null;
  81999. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82000. };
  82001. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82002. var _this = this;
  82003. //no dispose if no physics engine is available.
  82004. if (!this._physicsEngine) {
  82005. return;
  82006. }
  82007. this._joints.forEach(function (j) {
  82008. if (_this._physicsEngine) {
  82009. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82010. }
  82011. });
  82012. //dispose the physics body
  82013. this._physicsEngine.removeImpostor(this);
  82014. if (this.parent) {
  82015. this.parent.forceUpdate();
  82016. }
  82017. else {
  82018. /*this._object.getChildMeshes().forEach(function(mesh) {
  82019. if (mesh.physicsImpostor) {
  82020. if (disposeChildren) {
  82021. mesh.physicsImpostor.dispose();
  82022. mesh.physicsImpostor = null;
  82023. }
  82024. }
  82025. })*/
  82026. }
  82027. this._isDisposed = true;
  82028. };
  82029. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82030. this._deltaPosition.copyFrom(position);
  82031. };
  82032. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82033. if (!this._deltaRotation) {
  82034. this._deltaRotation = new BABYLON.Quaternion();
  82035. }
  82036. this._deltaRotation.copyFrom(rotation);
  82037. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82038. };
  82039. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82040. if (this._physicsEngine) {
  82041. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82042. }
  82043. return this;
  82044. };
  82045. PhysicsImpostor.prototype.getRadius = function () {
  82046. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82047. };
  82048. /**
  82049. * Sync a bone with this impostor
  82050. * @param bone The bone to sync to the impostor.
  82051. * @param boneMesh The mesh that the bone is influencing.
  82052. * @param jointPivot The pivot of the joint / bone in local space.
  82053. * @param distToJoint Optional distance from the impostor to the joint.
  82054. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82055. */
  82056. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82057. var tempVec = PhysicsImpostor._tmpVecs[0];
  82058. var mesh = this.object;
  82059. if (mesh.rotationQuaternion) {
  82060. if (adjustRotation) {
  82061. var tempQuat = PhysicsImpostor._tmpQuat;
  82062. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82063. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82064. }
  82065. else {
  82066. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82067. }
  82068. }
  82069. tempVec.x = 0;
  82070. tempVec.y = 0;
  82071. tempVec.z = 0;
  82072. if (jointPivot) {
  82073. tempVec.x = jointPivot.x;
  82074. tempVec.y = jointPivot.y;
  82075. tempVec.z = jointPivot.z;
  82076. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82077. if (distToJoint === undefined || distToJoint === null) {
  82078. distToJoint = jointPivot.length();
  82079. }
  82080. tempVec.x *= distToJoint;
  82081. tempVec.y *= distToJoint;
  82082. tempVec.z *= distToJoint;
  82083. }
  82084. if (bone.getParent()) {
  82085. tempVec.addInPlace(mesh.getAbsolutePosition());
  82086. bone.setAbsolutePosition(tempVec, boneMesh);
  82087. }
  82088. else {
  82089. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82090. boneMesh.position.x -= tempVec.x;
  82091. boneMesh.position.y -= tempVec.y;
  82092. boneMesh.position.z -= tempVec.z;
  82093. }
  82094. };
  82095. /**
  82096. * Sync impostor to a bone
  82097. * @param bone The bone that the impostor will be synced to.
  82098. * @param boneMesh The mesh that the bone is influencing.
  82099. * @param jointPivot The pivot of the joint / bone in local space.
  82100. * @param distToJoint Optional distance from the impostor to the joint.
  82101. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82102. * @param boneAxis Optional vector3 axis the bone is aligned with
  82103. */
  82104. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82105. var mesh = this.object;
  82106. if (mesh.rotationQuaternion) {
  82107. if (adjustRotation) {
  82108. var tempQuat = PhysicsImpostor._tmpQuat;
  82109. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82110. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82111. }
  82112. else {
  82113. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82114. }
  82115. }
  82116. var pos = PhysicsImpostor._tmpVecs[0];
  82117. var boneDir = PhysicsImpostor._tmpVecs[1];
  82118. if (!boneAxis) {
  82119. boneAxis = PhysicsImpostor._tmpVecs[2];
  82120. boneAxis.x = 0;
  82121. boneAxis.y = 1;
  82122. boneAxis.z = 0;
  82123. }
  82124. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82125. bone.getAbsolutePositionToRef(boneMesh, pos);
  82126. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82127. distToJoint = jointPivot.length();
  82128. }
  82129. if (distToJoint !== undefined && distToJoint !== null) {
  82130. pos.x += boneDir.x * distToJoint;
  82131. pos.y += boneDir.y * distToJoint;
  82132. pos.z += boneDir.z * distToJoint;
  82133. }
  82134. mesh.setAbsolutePosition(pos);
  82135. };
  82136. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82137. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82138. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82139. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82140. //Impostor types
  82141. PhysicsImpostor.NoImpostor = 0;
  82142. PhysicsImpostor.SphereImpostor = 1;
  82143. PhysicsImpostor.BoxImpostor = 2;
  82144. PhysicsImpostor.PlaneImpostor = 3;
  82145. PhysicsImpostor.MeshImpostor = 4;
  82146. PhysicsImpostor.CylinderImpostor = 7;
  82147. PhysicsImpostor.ParticleImpostor = 8;
  82148. PhysicsImpostor.HeightmapImpostor = 9;
  82149. return PhysicsImpostor;
  82150. }());
  82151. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82152. })(BABYLON || (BABYLON = {}));
  82153. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82154. var BABYLON;
  82155. (function (BABYLON) {
  82156. var PhysicsEngine = /** @class */ (function () {
  82157. function PhysicsEngine(gravity, _physicsPlugin) {
  82158. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82159. this._physicsPlugin = _physicsPlugin;
  82160. //new methods and parameters
  82161. this._impostors = [];
  82162. this._joints = [];
  82163. if (!this._physicsPlugin.isSupported()) {
  82164. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82165. + "Please make sure it is included.");
  82166. }
  82167. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82168. this.setGravity(gravity);
  82169. this.setTimeStep();
  82170. }
  82171. PhysicsEngine.prototype.setGravity = function (gravity) {
  82172. this.gravity = gravity;
  82173. this._physicsPlugin.setGravity(this.gravity);
  82174. };
  82175. /**
  82176. * Set the time step of the physics engine.
  82177. * default is 1/60.
  82178. * To slow it down, enter 1/600 for example.
  82179. * To speed it up, 1/30
  82180. * @param {number} newTimeStep the new timestep to apply to this world.
  82181. */
  82182. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82183. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82184. this._physicsPlugin.setTimeStep(newTimeStep);
  82185. };
  82186. /**
  82187. * Get the time step of the physics engine.
  82188. */
  82189. PhysicsEngine.prototype.getTimeStep = function () {
  82190. return this._physicsPlugin.getTimeStep();
  82191. };
  82192. PhysicsEngine.prototype.dispose = function () {
  82193. this._impostors.forEach(function (impostor) {
  82194. impostor.dispose();
  82195. });
  82196. this._physicsPlugin.dispose();
  82197. };
  82198. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82199. return this._physicsPlugin.name;
  82200. };
  82201. /**
  82202. * Adding a new impostor for the impostor tracking.
  82203. * This will be done by the impostor itself.
  82204. * @param {PhysicsImpostor} impostor the impostor to add
  82205. */
  82206. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82207. impostor.uniqueId = this._impostors.push(impostor);
  82208. //if no parent, generate the body
  82209. if (!impostor.parent) {
  82210. this._physicsPlugin.generatePhysicsBody(impostor);
  82211. }
  82212. };
  82213. /**
  82214. * Remove an impostor from the engine.
  82215. * This impostor and its mesh will not longer be updated by the physics engine.
  82216. * @param {PhysicsImpostor} impostor the impostor to remove
  82217. */
  82218. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82219. var index = this._impostors.indexOf(impostor);
  82220. if (index > -1) {
  82221. var removed = this._impostors.splice(index, 1);
  82222. //Is it needed?
  82223. if (removed.length) {
  82224. //this will also remove it from the world.
  82225. removed[0].physicsBody = null;
  82226. }
  82227. }
  82228. };
  82229. /**
  82230. * Add a joint to the physics engine
  82231. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82232. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82233. * @param {PhysicsJoint} the joint that will connect both impostors.
  82234. */
  82235. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82236. var impostorJoint = {
  82237. mainImpostor: mainImpostor,
  82238. connectedImpostor: connectedImpostor,
  82239. joint: joint
  82240. };
  82241. joint.physicsPlugin = this._physicsPlugin;
  82242. this._joints.push(impostorJoint);
  82243. this._physicsPlugin.generateJoint(impostorJoint);
  82244. };
  82245. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82246. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82247. return (impostorJoint.connectedImpostor === connectedImpostor
  82248. && impostorJoint.joint === joint
  82249. && impostorJoint.mainImpostor === mainImpostor);
  82250. });
  82251. if (matchingJoints.length) {
  82252. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82253. //TODO remove it from the list as well
  82254. }
  82255. };
  82256. /**
  82257. * Called by the scene. no need to call it.
  82258. */
  82259. PhysicsEngine.prototype._step = function (delta) {
  82260. var _this = this;
  82261. //check if any mesh has no body / requires an update
  82262. this._impostors.forEach(function (impostor) {
  82263. if (impostor.isBodyInitRequired()) {
  82264. _this._physicsPlugin.generatePhysicsBody(impostor);
  82265. }
  82266. });
  82267. if (delta > 0.1) {
  82268. delta = 0.1;
  82269. }
  82270. else if (delta <= 0) {
  82271. delta = 1.0 / 60.0;
  82272. }
  82273. this._physicsPlugin.executeStep(delta, this._impostors);
  82274. };
  82275. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82276. return this._physicsPlugin;
  82277. };
  82278. PhysicsEngine.prototype.getImpostors = function () {
  82279. return this._impostors;
  82280. };
  82281. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82282. for (var i = 0; i < this._impostors.length; ++i) {
  82283. if (this._impostors[i].object === object) {
  82284. return this._impostors[i];
  82285. }
  82286. }
  82287. return null;
  82288. };
  82289. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82290. for (var i = 0; i < this._impostors.length; ++i) {
  82291. if (this._impostors[i].physicsBody === body) {
  82292. return this._impostors[i];
  82293. }
  82294. }
  82295. return null;
  82296. };
  82297. // Statics
  82298. PhysicsEngine.Epsilon = 0.001;
  82299. return PhysicsEngine;
  82300. }());
  82301. BABYLON.PhysicsEngine = PhysicsEngine;
  82302. })(BABYLON || (BABYLON = {}));
  82303. //# sourceMappingURL=babylon.physicsEngine.js.map
  82304. var BABYLON;
  82305. (function (BABYLON) {
  82306. var PhysicsHelper = /** @class */ (function () {
  82307. function PhysicsHelper(scene) {
  82308. this._scene = scene;
  82309. this._physicsEngine = this._scene.getPhysicsEngine();
  82310. if (!this._physicsEngine) {
  82311. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82312. }
  82313. }
  82314. /**
  82315. * @param {Vector3} origin the origin of the explosion
  82316. * @param {number} radius the explosion radius
  82317. * @param {number} strength the explosion strength
  82318. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82319. */
  82320. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82321. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82322. if (!this._physicsEngine) {
  82323. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82324. return null;
  82325. }
  82326. var impostors = this._physicsEngine.getImpostors();
  82327. if (impostors.length === 0) {
  82328. return null;
  82329. }
  82330. var event = new PhysicsRadialExplosionEvent(this._scene);
  82331. impostors.forEach(function (impostor) {
  82332. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82333. if (!impostorForceAndContactPoint) {
  82334. return;
  82335. }
  82336. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82337. });
  82338. event.dispose(false);
  82339. return event;
  82340. };
  82341. /**
  82342. * @param {Vector3} origin the origin of the explosion
  82343. * @param {number} radius the explosion radius
  82344. * @param {number} strength the explosion strength
  82345. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82346. */
  82347. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82348. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82349. if (!this._physicsEngine) {
  82350. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82351. return null;
  82352. }
  82353. var impostors = this._physicsEngine.getImpostors();
  82354. if (impostors.length === 0) {
  82355. return null;
  82356. }
  82357. var event = new PhysicsRadialExplosionEvent(this._scene);
  82358. impostors.forEach(function (impostor) {
  82359. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82360. if (!impostorForceAndContactPoint) {
  82361. return;
  82362. }
  82363. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82364. });
  82365. event.dispose(false);
  82366. return event;
  82367. };
  82368. /**
  82369. * @param {Vector3} origin the origin of the explosion
  82370. * @param {number} radius the explosion radius
  82371. * @param {number} strength the explosion strength
  82372. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82373. */
  82374. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82375. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82376. if (!this._physicsEngine) {
  82377. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82378. return null;
  82379. }
  82380. var impostors = this._physicsEngine.getImpostors();
  82381. if (impostors.length === 0) {
  82382. return null;
  82383. }
  82384. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82385. event.dispose(false);
  82386. return event;
  82387. };
  82388. /**
  82389. * @param {Vector3} origin the origin of the updraft
  82390. * @param {number} radius the radius of the updraft
  82391. * @param {number} strength the strength of the updraft
  82392. * @param {number} height the height of the updraft
  82393. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82394. */
  82395. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82396. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82397. if (!this._physicsEngine) {
  82398. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82399. return null;
  82400. }
  82401. if (this._physicsEngine.getImpostors().length === 0) {
  82402. return null;
  82403. }
  82404. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82405. event.dispose(false);
  82406. return event;
  82407. };
  82408. /**
  82409. * @param {Vector3} origin the of the vortex
  82410. * @param {number} radius the radius of the vortex
  82411. * @param {number} strength the strength of the vortex
  82412. * @param {number} height the height of the vortex
  82413. */
  82414. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82415. if (!this._physicsEngine) {
  82416. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82417. return null;
  82418. }
  82419. if (this._physicsEngine.getImpostors().length === 0) {
  82420. return null;
  82421. }
  82422. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82423. event.dispose(false);
  82424. return event;
  82425. };
  82426. return PhysicsHelper;
  82427. }());
  82428. BABYLON.PhysicsHelper = PhysicsHelper;
  82429. /***** Radial explosion *****/
  82430. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82431. function PhysicsRadialExplosionEvent(scene) {
  82432. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82433. this._rays = [];
  82434. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82435. this._scene = scene;
  82436. }
  82437. /**
  82438. * Returns the data related to the radial explosion event (sphere & rays).
  82439. * @returns {PhysicsRadialExplosionEventData}
  82440. */
  82441. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82442. this._dataFetched = true;
  82443. return {
  82444. sphere: this._sphere,
  82445. rays: this._rays,
  82446. };
  82447. };
  82448. /**
  82449. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82450. * @param impostor
  82451. * @param {Vector3} origin the origin of the explosion
  82452. * @param {number} radius the explosion radius
  82453. * @param {number} strength the explosion strength
  82454. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82455. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82456. */
  82457. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82458. if (impostor.mass === 0) {
  82459. return null;
  82460. }
  82461. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82462. return null;
  82463. }
  82464. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82465. return null;
  82466. }
  82467. var impostorObjectCenter = impostor.getObjectCenter();
  82468. var direction = impostorObjectCenter.subtract(origin);
  82469. var ray = new BABYLON.Ray(origin, direction, radius);
  82470. this._rays.push(ray);
  82471. var hit = ray.intersectsMesh(impostor.object);
  82472. var contactPoint = hit.pickedPoint;
  82473. if (!contactPoint) {
  82474. return null;
  82475. }
  82476. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82477. if (distanceFromOrigin > radius) {
  82478. return null;
  82479. }
  82480. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82481. ? strength
  82482. : strength * (1 - (distanceFromOrigin / radius));
  82483. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82484. return { force: force, contactPoint: contactPoint };
  82485. };
  82486. /**
  82487. * Disposes the sphere.
  82488. * @param {bolean} force
  82489. */
  82490. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82491. var _this = this;
  82492. if (force === void 0) { force = true; }
  82493. if (force) {
  82494. this._sphere.dispose();
  82495. }
  82496. else {
  82497. setTimeout(function () {
  82498. if (!_this._dataFetched) {
  82499. _this._sphere.dispose();
  82500. }
  82501. }, 0);
  82502. }
  82503. };
  82504. /*** Helpers ***/
  82505. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82506. if (!this._sphere) {
  82507. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82508. this._sphere.isVisible = false;
  82509. }
  82510. };
  82511. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82512. var impostorObject = impostor.object;
  82513. this._prepareSphere();
  82514. this._sphere.position = origin;
  82515. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82516. this._sphere._updateBoundingInfo();
  82517. this._sphere.computeWorldMatrix(true);
  82518. return this._sphere.intersectsMesh(impostorObject, true);
  82519. };
  82520. return PhysicsRadialExplosionEvent;
  82521. }());
  82522. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82523. /***** Gravitational Field *****/
  82524. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82525. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82526. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82527. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82528. this._physicsHelper = physicsHelper;
  82529. this._scene = scene;
  82530. this._origin = origin;
  82531. this._radius = radius;
  82532. this._strength = strength;
  82533. this._falloff = falloff;
  82534. this._tickCallback = this._tick.bind(this);
  82535. }
  82536. /**
  82537. * Returns the data related to the gravitational field event (sphere).
  82538. * @returns {PhysicsGravitationalFieldEventData}
  82539. */
  82540. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82541. this._dataFetched = true;
  82542. return {
  82543. sphere: this._sphere,
  82544. };
  82545. };
  82546. /**
  82547. * Enables the gravitational field.
  82548. */
  82549. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82550. this._tickCallback.call(this);
  82551. this._scene.registerBeforeRender(this._tickCallback);
  82552. };
  82553. /**
  82554. * Disables the gravitational field.
  82555. */
  82556. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82557. this._scene.unregisterBeforeRender(this._tickCallback);
  82558. };
  82559. /**
  82560. * Disposes the sphere.
  82561. * @param {bolean} force
  82562. */
  82563. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82564. var _this = this;
  82565. if (force === void 0) { force = true; }
  82566. if (force) {
  82567. this._sphere.dispose();
  82568. }
  82569. else {
  82570. setTimeout(function () {
  82571. if (!_this._dataFetched) {
  82572. _this._sphere.dispose();
  82573. }
  82574. }, 0);
  82575. }
  82576. };
  82577. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82578. // Since the params won't change, we fetch the event only once
  82579. if (this._sphere) {
  82580. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82581. }
  82582. else {
  82583. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82584. if (radialExplosionEvent) {
  82585. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82586. }
  82587. }
  82588. };
  82589. return PhysicsGravitationalFieldEvent;
  82590. }());
  82591. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82592. /***** Updraft *****/
  82593. var PhysicsUpdraftEvent = /** @class */ (function () {
  82594. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82595. this._scene = _scene;
  82596. this._origin = _origin;
  82597. this._radius = _radius;
  82598. this._strength = _strength;
  82599. this._height = _height;
  82600. this._updraftMode = _updraftMode;
  82601. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82602. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82603. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82604. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82605. this._physicsEngine = this._scene.getPhysicsEngine();
  82606. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82607. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82608. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82609. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82610. }
  82611. this._tickCallback = this._tick.bind(this);
  82612. }
  82613. /**
  82614. * Returns the data related to the updraft event (cylinder).
  82615. * @returns {PhysicsUpdraftEventData}
  82616. */
  82617. PhysicsUpdraftEvent.prototype.getData = function () {
  82618. this._dataFetched = true;
  82619. return {
  82620. cylinder: this._cylinder,
  82621. };
  82622. };
  82623. /**
  82624. * Enables the updraft.
  82625. */
  82626. PhysicsUpdraftEvent.prototype.enable = function () {
  82627. this._tickCallback.call(this);
  82628. this._scene.registerBeforeRender(this._tickCallback);
  82629. };
  82630. /**
  82631. * Disables the cortex.
  82632. */
  82633. PhysicsUpdraftEvent.prototype.disable = function () {
  82634. this._scene.unregisterBeforeRender(this._tickCallback);
  82635. };
  82636. /**
  82637. * Disposes the sphere.
  82638. * @param {bolean} force
  82639. */
  82640. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82641. var _this = this;
  82642. if (force === void 0) { force = true; }
  82643. if (force) {
  82644. this._cylinder.dispose();
  82645. }
  82646. else {
  82647. setTimeout(function () {
  82648. if (!_this._dataFetched) {
  82649. _this._cylinder.dispose();
  82650. }
  82651. }, 0);
  82652. }
  82653. };
  82654. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82655. if (impostor.mass === 0) {
  82656. return null;
  82657. }
  82658. if (!this._intersectsWithCylinder(impostor)) {
  82659. return null;
  82660. }
  82661. var impostorObjectCenter = impostor.getObjectCenter();
  82662. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82663. var direction = this._originDirection;
  82664. }
  82665. else {
  82666. var direction = impostorObjectCenter.subtract(this._originTop);
  82667. }
  82668. var multiplier = this._strength * -1;
  82669. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82670. return { force: force, contactPoint: impostorObjectCenter };
  82671. };
  82672. PhysicsUpdraftEvent.prototype._tick = function () {
  82673. var _this = this;
  82674. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82675. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82676. if (!impostorForceAndContactPoint) {
  82677. return;
  82678. }
  82679. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82680. });
  82681. };
  82682. /*** Helpers ***/
  82683. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82684. if (!this._cylinder) {
  82685. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82686. height: this._height,
  82687. diameter: this._radius * 2,
  82688. }, this._scene);
  82689. this._cylinder.isVisible = false;
  82690. }
  82691. };
  82692. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82693. var impostorObject = impostor.object;
  82694. this._prepareCylinder();
  82695. this._cylinder.position = this._cylinderPosition;
  82696. return this._cylinder.intersectsMesh(impostorObject, true);
  82697. };
  82698. return PhysicsUpdraftEvent;
  82699. }());
  82700. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82701. /***** Vortex *****/
  82702. var PhysicsVortexEvent = /** @class */ (function () {
  82703. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82704. this._scene = _scene;
  82705. this._origin = _origin;
  82706. this._radius = _radius;
  82707. this._strength = _strength;
  82708. this._height = _height;
  82709. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82710. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82711. this._updraftMultiplier = 0.02;
  82712. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82713. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82714. this._physicsEngine = this._scene.getPhysicsEngine();
  82715. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82716. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82717. this._tickCallback = this._tick.bind(this);
  82718. }
  82719. /**
  82720. * Returns the data related to the vortex event (cylinder).
  82721. * @returns {PhysicsVortexEventData}
  82722. */
  82723. PhysicsVortexEvent.prototype.getData = function () {
  82724. this._dataFetched = true;
  82725. return {
  82726. cylinder: this._cylinder,
  82727. };
  82728. };
  82729. /**
  82730. * Enables the vortex.
  82731. */
  82732. PhysicsVortexEvent.prototype.enable = function () {
  82733. this._tickCallback.call(this);
  82734. this._scene.registerBeforeRender(this._tickCallback);
  82735. };
  82736. /**
  82737. * Disables the cortex.
  82738. */
  82739. PhysicsVortexEvent.prototype.disable = function () {
  82740. this._scene.unregisterBeforeRender(this._tickCallback);
  82741. };
  82742. /**
  82743. * Disposes the sphere.
  82744. * @param {bolean} force
  82745. */
  82746. PhysicsVortexEvent.prototype.dispose = function (force) {
  82747. var _this = this;
  82748. if (force === void 0) { force = true; }
  82749. if (force) {
  82750. this._cylinder.dispose();
  82751. }
  82752. else {
  82753. setTimeout(function () {
  82754. if (!_this._dataFetched) {
  82755. _this._cylinder.dispose();
  82756. }
  82757. }, 0);
  82758. }
  82759. };
  82760. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82761. if (impostor.mass === 0) {
  82762. return null;
  82763. }
  82764. if (!this._intersectsWithCylinder(impostor)) {
  82765. return null;
  82766. }
  82767. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82768. return null;
  82769. }
  82770. var impostorObjectCenter = impostor.getObjectCenter();
  82771. 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)
  82772. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82773. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82774. var hit = ray.intersectsMesh(impostor.object);
  82775. var contactPoint = hit.pickedPoint;
  82776. if (!contactPoint) {
  82777. return null;
  82778. }
  82779. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82780. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82781. var directionToOrigin = contactPoint.normalize();
  82782. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82783. directionToOrigin = directionToOrigin.negate();
  82784. }
  82785. // TODO: find a more physically based solution
  82786. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82787. var forceX = directionToOrigin.x * this._strength / 8;
  82788. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82789. var forceZ = directionToOrigin.z * this._strength / 8;
  82790. }
  82791. else {
  82792. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82793. var forceY = this._originTop.y * this._updraftMultiplier;
  82794. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82795. }
  82796. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82797. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82798. return { force: force, contactPoint: impostorObjectCenter };
  82799. };
  82800. PhysicsVortexEvent.prototype._tick = function () {
  82801. var _this = this;
  82802. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82803. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82804. if (!impostorForceAndContactPoint) {
  82805. return;
  82806. }
  82807. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82808. });
  82809. };
  82810. /*** Helpers ***/
  82811. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82812. if (!this._cylinder) {
  82813. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82814. height: this._height,
  82815. diameter: this._radius * 2,
  82816. }, this._scene);
  82817. this._cylinder.isVisible = false;
  82818. }
  82819. };
  82820. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82821. var impostorObject = impostor.object;
  82822. this._prepareCylinder();
  82823. this._cylinder.position = this._cylinderPosition;
  82824. return this._cylinder.intersectsMesh(impostorObject, true);
  82825. };
  82826. return PhysicsVortexEvent;
  82827. }());
  82828. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82829. /***** Enums *****/
  82830. /**
  82831. * The strenght of the force in correspondence to the distance of the affected object
  82832. */
  82833. var PhysicsRadialImpulseFalloff;
  82834. (function (PhysicsRadialImpulseFalloff) {
  82835. /** Defines that impulse is constant in strength across it's whole radius */
  82836. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82837. /** DEfines that impulse gets weaker if it's further from the origin */
  82838. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82839. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82840. /**
  82841. * The strenght of the force in correspondence to the distance of the affected object
  82842. */
  82843. var PhysicsUpdraftMode;
  82844. (function (PhysicsUpdraftMode) {
  82845. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82846. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82847. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82848. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  82849. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82850. })(BABYLON || (BABYLON = {}));
  82851. //# sourceMappingURL=babylon.physicsHelper.js.map
  82852. var BABYLON;
  82853. (function (BABYLON) {
  82854. var CannonJSPlugin = /** @class */ (function () {
  82855. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82856. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82857. if (iterations === void 0) { iterations = 10; }
  82858. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82859. this.name = "CannonJSPlugin";
  82860. this._physicsMaterials = new Array();
  82861. this._fixedTimeStep = 1 / 60;
  82862. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82863. this.BJSCANNON = CANNON;
  82864. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82865. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82866. this._tmpPosition = BABYLON.Vector3.Zero();
  82867. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82868. this._tmpUnityRotation = new BABYLON.Quaternion();
  82869. if (!this.isSupported()) {
  82870. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82871. return;
  82872. }
  82873. this._extendNamespace();
  82874. this.world = new this.BJSCANNON.World();
  82875. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  82876. this.world.solver.iterations = iterations;
  82877. }
  82878. CannonJSPlugin.prototype.setGravity = function (gravity) {
  82879. this.world.gravity.copy(gravity);
  82880. };
  82881. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  82882. this._fixedTimeStep = timeStep;
  82883. };
  82884. CannonJSPlugin.prototype.getTimeStep = function () {
  82885. return this._fixedTimeStep;
  82886. };
  82887. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  82888. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  82889. };
  82890. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82891. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82892. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82893. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  82894. };
  82895. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82896. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82897. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82898. impostor.physicsBody.applyForce(impulse, worldPoint);
  82899. };
  82900. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82901. //parent-child relationship. Does this impostor has a parent impostor?
  82902. if (impostor.parent) {
  82903. if (impostor.physicsBody) {
  82904. this.removePhysicsBody(impostor);
  82905. //TODO is that needed?
  82906. impostor.forceUpdate();
  82907. }
  82908. return;
  82909. }
  82910. //should a new body be created for this impostor?
  82911. if (impostor.isBodyInitRequired()) {
  82912. var shape = this._createShape(impostor);
  82913. //unregister events, if body is being changed
  82914. var oldBody = impostor.physicsBody;
  82915. if (oldBody) {
  82916. this.removePhysicsBody(impostor);
  82917. }
  82918. //create the body and material
  82919. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  82920. var bodyCreationObject = {
  82921. mass: impostor.getParam("mass"),
  82922. material: material
  82923. };
  82924. // A simple extend, in case native options were used.
  82925. var nativeOptions = impostor.getParam("nativeOptions");
  82926. for (var key in nativeOptions) {
  82927. if (nativeOptions.hasOwnProperty(key)) {
  82928. bodyCreationObject[key] = nativeOptions[key];
  82929. }
  82930. }
  82931. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  82932. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  82933. this.world.addEventListener("preStep", impostor.beforeStep);
  82934. this.world.addEventListener("postStep", impostor.afterStep);
  82935. impostor.physicsBody.addShape(shape);
  82936. this.world.add(impostor.physicsBody);
  82937. //try to keep the body moving in the right direction by taking old properties.
  82938. //Should be tested!
  82939. if (oldBody) {
  82940. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  82941. impostor.physicsBody[param].copy(oldBody[param]);
  82942. });
  82943. }
  82944. this._processChildMeshes(impostor);
  82945. }
  82946. //now update the body's transformation
  82947. this._updatePhysicsBodyTransformation(impostor);
  82948. };
  82949. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  82950. var _this = this;
  82951. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  82952. var currentRotation = mainImpostor.object.rotationQuaternion;
  82953. if (meshChildren.length) {
  82954. var processMesh = function (localPosition, mesh) {
  82955. if (!currentRotation || !mesh.rotationQuaternion) {
  82956. return;
  82957. }
  82958. var childImpostor = mesh.getPhysicsImpostor();
  82959. if (childImpostor) {
  82960. var parent = childImpostor.parent;
  82961. if (parent !== mainImpostor) {
  82962. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  82963. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  82964. if (childImpostor.physicsBody) {
  82965. _this.removePhysicsBody(childImpostor);
  82966. childImpostor.physicsBody = null;
  82967. }
  82968. childImpostor.parent = mainImpostor;
  82969. childImpostor.resetUpdateFlags();
  82970. 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));
  82971. //Add the mass of the children.
  82972. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  82973. }
  82974. }
  82975. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  82976. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  82977. };
  82978. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  82979. }
  82980. };
  82981. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  82982. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  82983. this.world.removeEventListener("preStep", impostor.beforeStep);
  82984. this.world.removeEventListener("postStep", impostor.afterStep);
  82985. this.world.remove(impostor.physicsBody);
  82986. };
  82987. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  82988. var mainBody = impostorJoint.mainImpostor.physicsBody;
  82989. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  82990. if (!mainBody || !connectedBody) {
  82991. return;
  82992. }
  82993. var constraint;
  82994. var jointData = impostorJoint.joint.jointData;
  82995. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  82996. var constraintData = {
  82997. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  82998. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  82999. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83000. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83001. maxForce: jointData.nativeParams.maxForce,
  83002. collideConnected: !!jointData.collision
  83003. };
  83004. switch (impostorJoint.joint.type) {
  83005. case BABYLON.PhysicsJoint.HingeJoint:
  83006. case BABYLON.PhysicsJoint.Hinge2Joint:
  83007. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83008. break;
  83009. case BABYLON.PhysicsJoint.DistanceJoint:
  83010. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83011. break;
  83012. case BABYLON.PhysicsJoint.SpringJoint:
  83013. var springData = jointData;
  83014. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83015. restLength: springData.length,
  83016. stiffness: springData.stiffness,
  83017. damping: springData.damping,
  83018. localAnchorA: constraintData.pivotA,
  83019. localAnchorB: constraintData.pivotB
  83020. });
  83021. break;
  83022. case BABYLON.PhysicsJoint.LockJoint:
  83023. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83024. break;
  83025. case BABYLON.PhysicsJoint.PointToPointJoint:
  83026. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83027. default:
  83028. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83029. break;
  83030. }
  83031. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83032. constraint.collideConnected = !!jointData.collision;
  83033. impostorJoint.joint.physicsJoint = constraint;
  83034. //don't add spring as constraint, as it is not one.
  83035. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83036. this.world.addConstraint(constraint);
  83037. }
  83038. else {
  83039. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83040. constraint.applyForce();
  83041. });
  83042. }
  83043. };
  83044. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83045. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83046. };
  83047. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83048. var index;
  83049. var mat;
  83050. for (index = 0; index < this._physicsMaterials.length; index++) {
  83051. mat = this._physicsMaterials[index];
  83052. if (mat.friction === friction && mat.restitution === restitution) {
  83053. return mat;
  83054. }
  83055. }
  83056. var currentMat = new this.BJSCANNON.Material(name);
  83057. currentMat.friction = friction;
  83058. currentMat.restitution = restitution;
  83059. this._physicsMaterials.push(currentMat);
  83060. return currentMat;
  83061. };
  83062. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83063. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83064. };
  83065. CannonJSPlugin.prototype._createShape = function (impostor) {
  83066. var object = impostor.object;
  83067. var returnValue;
  83068. var extendSize = impostor.getObjectExtendSize();
  83069. switch (impostor.type) {
  83070. case BABYLON.PhysicsImpostor.SphereImpostor:
  83071. var radiusX = extendSize.x;
  83072. var radiusY = extendSize.y;
  83073. var radiusZ = extendSize.z;
  83074. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83075. break;
  83076. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83077. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83078. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83079. break;
  83080. case BABYLON.PhysicsImpostor.BoxImpostor:
  83081. var box = extendSize.scale(0.5);
  83082. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83083. break;
  83084. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83085. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83086. returnValue = new this.BJSCANNON.Plane();
  83087. break;
  83088. case BABYLON.PhysicsImpostor.MeshImpostor:
  83089. // should transform the vertex data to world coordinates!!
  83090. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83091. var rawFaces = object.getIndices ? object.getIndices() : [];
  83092. if (!rawVerts)
  83093. return;
  83094. // get only scale! so the object could transform correctly.
  83095. var oldPosition = object.position.clone();
  83096. var oldRotation = object.rotation && object.rotation.clone();
  83097. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83098. object.position.copyFromFloats(0, 0, 0);
  83099. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83100. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83101. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83102. var transform = object.computeWorldMatrix(true);
  83103. // convert rawVerts to object space
  83104. var temp = new Array();
  83105. var index;
  83106. for (index = 0; index < rawVerts.length; index += 3) {
  83107. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83108. }
  83109. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83110. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83111. //now set back the transformation!
  83112. object.position.copyFrom(oldPosition);
  83113. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83114. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83115. break;
  83116. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83117. var oldPosition2 = object.position.clone();
  83118. var oldRotation2 = object.rotation && object.rotation.clone();
  83119. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83120. object.position.copyFromFloats(0, 0, 0);
  83121. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83122. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83123. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83124. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83125. returnValue = this._createHeightmap(object);
  83126. object.position.copyFrom(oldPosition2);
  83127. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83128. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83129. object.computeWorldMatrix(true);
  83130. break;
  83131. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83132. returnValue = new this.BJSCANNON.Particle();
  83133. break;
  83134. }
  83135. return returnValue;
  83136. };
  83137. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83138. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83139. var transform = object.computeWorldMatrix(true);
  83140. // convert rawVerts to object space
  83141. var temp = new Array();
  83142. var index;
  83143. for (index = 0; index < pos.length; index += 3) {
  83144. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83145. }
  83146. pos = temp;
  83147. var matrix = new Array();
  83148. //For now pointDepth will not be used and will be automatically calculated.
  83149. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83150. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83151. var boundingInfo = object.getBoundingInfo();
  83152. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83153. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83154. var elementSize = dim * 2 / arraySize;
  83155. for (var i = 0; i < pos.length; i = i + 3) {
  83156. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83157. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83158. var y = -pos[i + 2] + minY;
  83159. if (!matrix[x]) {
  83160. matrix[x] = [];
  83161. }
  83162. if (!matrix[x][z]) {
  83163. matrix[x][z] = y;
  83164. }
  83165. matrix[x][z] = Math.max(y, matrix[x][z]);
  83166. }
  83167. for (var x = 0; x <= arraySize; ++x) {
  83168. if (!matrix[x]) {
  83169. var loc = 1;
  83170. while (!matrix[(x + loc) % arraySize]) {
  83171. loc++;
  83172. }
  83173. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83174. //console.log("missing x", x);
  83175. }
  83176. for (var z = 0; z <= arraySize; ++z) {
  83177. if (!matrix[x][z]) {
  83178. var loc = 1;
  83179. var newValue;
  83180. while (newValue === undefined) {
  83181. newValue = matrix[x][(z + loc++) % arraySize];
  83182. }
  83183. matrix[x][z] = newValue;
  83184. }
  83185. }
  83186. }
  83187. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83188. elementSize: elementSize
  83189. });
  83190. //For future reference, needed for body transformation
  83191. shape.minY = minY;
  83192. return shape;
  83193. };
  83194. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83195. var object = impostor.object;
  83196. //make sure it is updated...
  83197. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83198. // The delta between the mesh position and the mesh bounding box center
  83199. var bInfo = object.getBoundingInfo();
  83200. if (!bInfo)
  83201. return;
  83202. var center = impostor.getObjectCenter();
  83203. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83204. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83205. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83206. this._tmpPosition.copyFrom(center);
  83207. var quaternion = object.rotationQuaternion;
  83208. if (!quaternion) {
  83209. return;
  83210. }
  83211. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83212. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83213. //-90 DEG in X, precalculated
  83214. quaternion = quaternion.multiply(this._minus90X);
  83215. //Invert! (Precalculated, 90 deg in X)
  83216. //No need to clone. this will never change.
  83217. impostor.setDeltaRotation(this._plus90X);
  83218. }
  83219. //If it is a heightfield, if should be centered.
  83220. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83221. var mesh = object;
  83222. var boundingInfo = mesh.getBoundingInfo();
  83223. //calculate the correct body position:
  83224. var rotationQuaternion = mesh.rotationQuaternion;
  83225. mesh.rotationQuaternion = this._tmpUnityRotation;
  83226. mesh.computeWorldMatrix(true);
  83227. //get original center with no rotation
  83228. var c = center.clone();
  83229. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83230. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83231. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83232. mesh.setPreTransformMatrix(p);
  83233. mesh.computeWorldMatrix(true);
  83234. //calculate the translation
  83235. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83236. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83237. //add it inverted to the delta
  83238. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83239. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83240. //rotation is back
  83241. mesh.rotationQuaternion = rotationQuaternion;
  83242. mesh.setPreTransformMatrix(oldPivot);
  83243. mesh.computeWorldMatrix(true);
  83244. }
  83245. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83246. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83247. //this._tmpPosition.copyFrom(object.position);
  83248. }
  83249. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83250. //Now update the impostor object
  83251. impostor.physicsBody.position.copy(this._tmpPosition);
  83252. impostor.physicsBody.quaternion.copy(quaternion);
  83253. };
  83254. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83255. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83256. if (impostor.object.rotationQuaternion) {
  83257. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83258. }
  83259. };
  83260. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83261. impostor.physicsBody.position.copy(newPosition);
  83262. impostor.physicsBody.quaternion.copy(newRotation);
  83263. };
  83264. CannonJSPlugin.prototype.isSupported = function () {
  83265. return this.BJSCANNON !== undefined;
  83266. };
  83267. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83268. impostor.physicsBody.velocity.copy(velocity);
  83269. };
  83270. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83271. impostor.physicsBody.angularVelocity.copy(velocity);
  83272. };
  83273. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83274. var v = impostor.physicsBody.velocity;
  83275. if (!v) {
  83276. return null;
  83277. }
  83278. return new BABYLON.Vector3(v.x, v.y, v.z);
  83279. };
  83280. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83281. var v = impostor.physicsBody.angularVelocity;
  83282. if (!v) {
  83283. return null;
  83284. }
  83285. return new BABYLON.Vector3(v.x, v.y, v.z);
  83286. };
  83287. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83288. impostor.physicsBody.mass = mass;
  83289. impostor.physicsBody.updateMassProperties();
  83290. };
  83291. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83292. return impostor.physicsBody.mass;
  83293. };
  83294. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83295. return impostor.physicsBody.material.friction;
  83296. };
  83297. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83298. impostor.physicsBody.material.friction = friction;
  83299. };
  83300. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83301. return impostor.physicsBody.material.restitution;
  83302. };
  83303. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83304. impostor.physicsBody.material.restitution = restitution;
  83305. };
  83306. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83307. impostor.physicsBody.sleep();
  83308. };
  83309. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83310. impostor.physicsBody.wakeUp();
  83311. };
  83312. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83313. joint.physicsJoint.distance = maxDistance;
  83314. };
  83315. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83316. // if (!motorIndex) {
  83317. // joint.physicsJoint.enableMotor();
  83318. // }
  83319. // }
  83320. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83321. // if (!motorIndex) {
  83322. // joint.physicsJoint.disableMotor();
  83323. // }
  83324. // }
  83325. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83326. if (!motorIndex) {
  83327. joint.physicsJoint.enableMotor();
  83328. joint.physicsJoint.setMotorSpeed(speed);
  83329. if (maxForce) {
  83330. this.setLimit(joint, maxForce);
  83331. }
  83332. }
  83333. };
  83334. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83335. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83336. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83337. };
  83338. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83339. var body = impostor.physicsBody;
  83340. mesh.position.x = body.position.x;
  83341. mesh.position.y = body.position.y;
  83342. mesh.position.z = body.position.z;
  83343. if (mesh.rotationQuaternion) {
  83344. mesh.rotationQuaternion.x = body.quaternion.x;
  83345. mesh.rotationQuaternion.y = body.quaternion.y;
  83346. mesh.rotationQuaternion.z = body.quaternion.z;
  83347. mesh.rotationQuaternion.w = body.quaternion.w;
  83348. }
  83349. };
  83350. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83351. var shape = impostor.physicsBody.shapes[0];
  83352. return shape.boundingSphereRadius;
  83353. };
  83354. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83355. var shape = impostor.physicsBody.shapes[0];
  83356. result.x = shape.halfExtents.x * 2;
  83357. result.y = shape.halfExtents.y * 2;
  83358. result.z = shape.halfExtents.z * 2;
  83359. };
  83360. CannonJSPlugin.prototype.dispose = function () {
  83361. };
  83362. CannonJSPlugin.prototype._extendNamespace = function () {
  83363. //this will force cannon to execute at least one step when using interpolation
  83364. var step_tmp1 = new this.BJSCANNON.Vec3();
  83365. var Engine = this.BJSCANNON;
  83366. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83367. maxSubSteps = maxSubSteps || 10;
  83368. timeSinceLastCalled = timeSinceLastCalled || 0;
  83369. if (timeSinceLastCalled === 0) {
  83370. this.internalStep(dt);
  83371. this.time += dt;
  83372. }
  83373. else {
  83374. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83375. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83376. var t0 = performance.now();
  83377. for (var i = 0; i !== internalSteps; i++) {
  83378. this.internalStep(dt);
  83379. if (performance.now() - t0 > dt * 1000) {
  83380. break;
  83381. }
  83382. }
  83383. this.time += timeSinceLastCalled;
  83384. var h = this.time % dt;
  83385. var h_div_dt = h / dt;
  83386. var interpvelo = step_tmp1;
  83387. var bodies = this.bodies;
  83388. for (var j = 0; j !== bodies.length; j++) {
  83389. var b = bodies[j];
  83390. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83391. b.position.vsub(b.previousPosition, interpvelo);
  83392. interpvelo.scale(h_div_dt, interpvelo);
  83393. b.position.vadd(interpvelo, b.interpolatedPosition);
  83394. }
  83395. else {
  83396. b.interpolatedPosition.copy(b.position);
  83397. b.interpolatedQuaternion.copy(b.quaternion);
  83398. }
  83399. }
  83400. }
  83401. };
  83402. };
  83403. return CannonJSPlugin;
  83404. }());
  83405. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83406. })(BABYLON || (BABYLON = {}));
  83407. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83408. var BABYLON;
  83409. (function (BABYLON) {
  83410. var OimoJSPlugin = /** @class */ (function () {
  83411. function OimoJSPlugin(iterations) {
  83412. this.name = "OimoJSPlugin";
  83413. this._tmpImpostorsArray = [];
  83414. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83415. this.BJSOIMO = OIMO;
  83416. this.world = new this.BJSOIMO.World({
  83417. iterations: iterations
  83418. });
  83419. this.world.clear();
  83420. }
  83421. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83422. this.world.gravity.copy(gravity);
  83423. };
  83424. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83425. this.world.timeStep = timeStep;
  83426. };
  83427. OimoJSPlugin.prototype.getTimeStep = function () {
  83428. return this.world.timeStep;
  83429. };
  83430. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83431. var _this = this;
  83432. impostors.forEach(function (impostor) {
  83433. impostor.beforeStep();
  83434. });
  83435. this.world.step();
  83436. impostors.forEach(function (impostor) {
  83437. impostor.afterStep();
  83438. //update the ordered impostors array
  83439. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83440. });
  83441. //check for collisions
  83442. var contact = this.world.contacts;
  83443. while (contact !== null) {
  83444. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83445. contact = contact.next;
  83446. continue;
  83447. }
  83448. //is this body colliding with any other? get the impostor
  83449. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83450. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83451. if (!mainImpostor || !collidingImpostor) {
  83452. contact = contact.next;
  83453. continue;
  83454. }
  83455. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83456. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83457. contact = contact.next;
  83458. }
  83459. };
  83460. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83461. var mass = impostor.physicsBody.mass;
  83462. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83463. };
  83464. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83465. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83466. this.applyImpulse(impostor, force, contactPoint);
  83467. };
  83468. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83469. var _this = this;
  83470. //parent-child relationship. Does this impostor has a parent impostor?
  83471. if (impostor.parent) {
  83472. if (impostor.physicsBody) {
  83473. this.removePhysicsBody(impostor);
  83474. //TODO is that needed?
  83475. impostor.forceUpdate();
  83476. }
  83477. return;
  83478. }
  83479. if (impostor.isBodyInitRequired()) {
  83480. var bodyConfig = {
  83481. name: impostor.uniqueId,
  83482. //Oimo must have mass, also for static objects.
  83483. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83484. size: [],
  83485. type: [],
  83486. pos: [],
  83487. posShape: [],
  83488. rot: [],
  83489. rotShape: [],
  83490. move: impostor.getParam("mass") !== 0,
  83491. density: impostor.getParam("mass"),
  83492. friction: impostor.getParam("friction"),
  83493. restitution: impostor.getParam("restitution"),
  83494. //Supporting older versions of Oimo
  83495. world: this.world
  83496. };
  83497. var impostors = [impostor];
  83498. var addToArray = function (parent) {
  83499. if (!parent.getChildMeshes)
  83500. return;
  83501. parent.getChildMeshes().forEach(function (m) {
  83502. if (m.physicsImpostor) {
  83503. impostors.push(m.physicsImpostor);
  83504. //m.physicsImpostor._init();
  83505. }
  83506. });
  83507. };
  83508. addToArray(impostor.object);
  83509. var checkWithEpsilon_1 = function (value) {
  83510. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83511. };
  83512. impostors.forEach(function (i) {
  83513. if (!i.object.rotationQuaternion) {
  83514. return;
  83515. }
  83516. //get the correct bounding box
  83517. var oldQuaternion = i.object.rotationQuaternion;
  83518. var rot = oldQuaternion.toEulerAngles();
  83519. var extendSize = i.getObjectExtendSize();
  83520. var radToDeg = 57.295779513082320876;
  83521. if (i === impostor) {
  83522. var center = impostor.getObjectCenter();
  83523. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83524. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83525. //Can also use Array.prototype.push.apply
  83526. bodyConfig.pos.push(center.x);
  83527. bodyConfig.pos.push(center.y);
  83528. bodyConfig.pos.push(center.z);
  83529. bodyConfig.posShape.push(0, 0, 0);
  83530. //tmp solution
  83531. bodyConfig.rot.push(rot.x * radToDeg);
  83532. bodyConfig.rot.push(rot.y * radToDeg);
  83533. bodyConfig.rot.push(rot.z * radToDeg);
  83534. bodyConfig.rotShape.push(0, 0, 0);
  83535. }
  83536. else {
  83537. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83538. bodyConfig.posShape.push(localPosition.x);
  83539. bodyConfig.posShape.push(localPosition.y);
  83540. bodyConfig.posShape.push(localPosition.z);
  83541. bodyConfig.pos.push(0, 0, 0);
  83542. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83543. bodyConfig.rot.push(0);
  83544. bodyConfig.rot.push(0);
  83545. bodyConfig.rot.push(0);
  83546. bodyConfig.rotShape.push(rot.x * radToDeg);
  83547. bodyConfig.rotShape.push(rot.y * radToDeg);
  83548. bodyConfig.rotShape.push(rot.z * radToDeg);
  83549. }
  83550. // register mesh
  83551. switch (i.type) {
  83552. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83553. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83554. case BABYLON.PhysicsImpostor.SphereImpostor:
  83555. var radiusX = extendSize.x;
  83556. var radiusY = extendSize.y;
  83557. var radiusZ = extendSize.z;
  83558. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83559. bodyConfig.type.push('sphere');
  83560. //due to the way oimo works with compounds, add 3 times
  83561. bodyConfig.size.push(size);
  83562. bodyConfig.size.push(size);
  83563. bodyConfig.size.push(size);
  83564. break;
  83565. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83566. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83567. var sizeY = checkWithEpsilon_1(extendSize.y);
  83568. bodyConfig.type.push('cylinder');
  83569. bodyConfig.size.push(sizeX);
  83570. bodyConfig.size.push(sizeY);
  83571. //due to the way oimo works with compounds, add one more value.
  83572. bodyConfig.size.push(sizeY);
  83573. break;
  83574. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83575. case BABYLON.PhysicsImpostor.BoxImpostor:
  83576. default:
  83577. var sizeX = checkWithEpsilon_1(extendSize.x);
  83578. var sizeY = checkWithEpsilon_1(extendSize.y);
  83579. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83580. bodyConfig.type.push('box');
  83581. //if (i === impostor) {
  83582. bodyConfig.size.push(sizeX);
  83583. bodyConfig.size.push(sizeY);
  83584. bodyConfig.size.push(sizeZ);
  83585. //} else {
  83586. // bodyConfig.size.push(0,0,0);
  83587. //}
  83588. break;
  83589. }
  83590. //actually not needed, but hey...
  83591. i.object.rotationQuaternion = oldQuaternion;
  83592. });
  83593. impostor.physicsBody = this.world.add(bodyConfig);
  83594. }
  83595. else {
  83596. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83597. }
  83598. impostor.setDeltaPosition(this._tmpPositionVector);
  83599. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83600. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83601. };
  83602. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83603. //impostor.physicsBody.dispose();
  83604. //Same as : (older oimo versions)
  83605. this.world.removeRigidBody(impostor.physicsBody);
  83606. };
  83607. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83608. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83609. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83610. if (!mainBody || !connectedBody) {
  83611. return;
  83612. }
  83613. var jointData = impostorJoint.joint.jointData;
  83614. var options = jointData.nativeParams || {};
  83615. var type;
  83616. var nativeJointData = {
  83617. body1: mainBody,
  83618. body2: connectedBody,
  83619. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83620. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83621. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83622. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83623. min: options.min,
  83624. max: options.max,
  83625. collision: options.collision || jointData.collision,
  83626. spring: options.spring,
  83627. //supporting older version of Oimo
  83628. world: this.world
  83629. };
  83630. switch (impostorJoint.joint.type) {
  83631. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83632. type = "jointBall";
  83633. break;
  83634. case BABYLON.PhysicsJoint.SpringJoint:
  83635. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83636. var springData = jointData;
  83637. nativeJointData.min = springData.length || nativeJointData.min;
  83638. //Max should also be set, just make sure it is at least min
  83639. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83640. case BABYLON.PhysicsJoint.DistanceJoint:
  83641. type = "jointDistance";
  83642. nativeJointData.max = jointData.maxDistance;
  83643. break;
  83644. case BABYLON.PhysicsJoint.PrismaticJoint:
  83645. type = "jointPrisme";
  83646. break;
  83647. case BABYLON.PhysicsJoint.SliderJoint:
  83648. type = "jointSlide";
  83649. break;
  83650. case BABYLON.PhysicsJoint.WheelJoint:
  83651. type = "jointWheel";
  83652. break;
  83653. case BABYLON.PhysicsJoint.HingeJoint:
  83654. default:
  83655. type = "jointHinge";
  83656. break;
  83657. }
  83658. nativeJointData.type = type;
  83659. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83660. };
  83661. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83662. //Bug in Oimo prevents us from disposing a joint in the playground
  83663. //joint.joint.physicsJoint.dispose();
  83664. //So we will bruteforce it!
  83665. try {
  83666. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83667. }
  83668. catch (e) {
  83669. BABYLON.Tools.Warn(e);
  83670. }
  83671. };
  83672. OimoJSPlugin.prototype.isSupported = function () {
  83673. return this.BJSOIMO !== undefined;
  83674. };
  83675. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83676. if (!impostor.physicsBody.sleeping) {
  83677. //TODO check that
  83678. /*if (impostor.physicsBody.shapes.next) {
  83679. var parentShape = this._getLastShape(impostor.physicsBody);
  83680. impostor.object.position.copyFrom(parentShape.position);
  83681. console.log(parentShape.position);
  83682. } else {*/
  83683. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83684. //}
  83685. if (impostor.object.rotationQuaternion) {
  83686. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83687. }
  83688. }
  83689. };
  83690. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83691. var body = impostor.physicsBody;
  83692. body.position.copy(newPosition);
  83693. body.orientation.copy(newRotation);
  83694. body.syncShapes();
  83695. body.awake();
  83696. };
  83697. /*private _getLastShape(body: any): any {
  83698. var lastShape = body.shapes;
  83699. while (lastShape.next) {
  83700. lastShape = lastShape.next;
  83701. }
  83702. return lastShape;
  83703. }*/
  83704. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83705. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83706. };
  83707. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83708. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83709. };
  83710. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83711. var v = impostor.physicsBody.linearVelocity;
  83712. if (!v) {
  83713. return null;
  83714. }
  83715. return new BABYLON.Vector3(v.x, v.y, v.z);
  83716. };
  83717. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83718. var v = impostor.physicsBody.angularVelocity;
  83719. if (!v) {
  83720. return null;
  83721. }
  83722. return new BABYLON.Vector3(v.x, v.y, v.z);
  83723. };
  83724. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83725. var staticBody = mass === 0;
  83726. //this will actually set the body's density and not its mass.
  83727. //But this is how oimo treats the mass variable.
  83728. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83729. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83730. };
  83731. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83732. return impostor.physicsBody.shapes.density;
  83733. };
  83734. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83735. return impostor.physicsBody.shapes.friction;
  83736. };
  83737. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83738. impostor.physicsBody.shapes.friction = friction;
  83739. };
  83740. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83741. return impostor.physicsBody.shapes.restitution;
  83742. };
  83743. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83744. impostor.physicsBody.shapes.restitution = restitution;
  83745. };
  83746. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83747. impostor.physicsBody.sleep();
  83748. };
  83749. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83750. impostor.physicsBody.awake();
  83751. };
  83752. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83753. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83754. if (minDistance !== void 0) {
  83755. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83756. }
  83757. };
  83758. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83759. //TODO separate rotational and transational motors.
  83760. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83761. if (motor) {
  83762. motor.setMotor(speed, maxForce);
  83763. }
  83764. };
  83765. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83766. //TODO separate rotational and transational motors.
  83767. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83768. if (motor) {
  83769. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83770. }
  83771. };
  83772. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83773. var body = impostor.physicsBody;
  83774. mesh.position.x = body.position.x;
  83775. mesh.position.y = body.position.y;
  83776. mesh.position.z = body.position.z;
  83777. if (mesh.rotationQuaternion) {
  83778. mesh.rotationQuaternion.x = body.orientation.x;
  83779. mesh.rotationQuaternion.y = body.orientation.y;
  83780. mesh.rotationQuaternion.z = body.orientation.z;
  83781. mesh.rotationQuaternion.w = body.orientation.s;
  83782. }
  83783. };
  83784. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83785. return impostor.physicsBody.shapes.radius;
  83786. };
  83787. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83788. var shape = impostor.physicsBody.shapes;
  83789. result.x = shape.halfWidth * 2;
  83790. result.y = shape.halfHeight * 2;
  83791. result.z = shape.halfDepth * 2;
  83792. };
  83793. OimoJSPlugin.prototype.dispose = function () {
  83794. this.world.clear();
  83795. };
  83796. return OimoJSPlugin;
  83797. }());
  83798. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83799. })(BABYLON || (BABYLON = {}));
  83800. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83801. var BABYLON;
  83802. (function (BABYLON) {
  83803. /*
  83804. * Based on jsTGALoader - Javascript loader for TGA file
  83805. * By Vincent Thibault
  83806. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83807. */
  83808. var TGATools = /** @class */ (function () {
  83809. function TGATools() {
  83810. }
  83811. TGATools.GetTGAHeader = function (data) {
  83812. var offset = 0;
  83813. var header = {
  83814. id_length: data[offset++],
  83815. colormap_type: data[offset++],
  83816. image_type: data[offset++],
  83817. colormap_index: data[offset++] | data[offset++] << 8,
  83818. colormap_length: data[offset++] | data[offset++] << 8,
  83819. colormap_size: data[offset++],
  83820. origin: [
  83821. data[offset++] | data[offset++] << 8,
  83822. data[offset++] | data[offset++] << 8
  83823. ],
  83824. width: data[offset++] | data[offset++] << 8,
  83825. height: data[offset++] | data[offset++] << 8,
  83826. pixel_size: data[offset++],
  83827. flags: data[offset++]
  83828. };
  83829. return header;
  83830. };
  83831. TGATools.UploadContent = function (gl, data) {
  83832. // Not enough data to contain header ?
  83833. if (data.length < 19) {
  83834. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83835. return;
  83836. }
  83837. // Read Header
  83838. var offset = 18;
  83839. var header = TGATools.GetTGAHeader(data);
  83840. // Assume it's a valid Targa file.
  83841. if (header.id_length + offset > data.length) {
  83842. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83843. return;
  83844. }
  83845. // Skip not needed data
  83846. offset += header.id_length;
  83847. var use_rle = false;
  83848. var use_pal = false;
  83849. var use_grey = false;
  83850. // Get some informations.
  83851. switch (header.image_type) {
  83852. case TGATools._TYPE_RLE_INDEXED:
  83853. use_rle = true;
  83854. case TGATools._TYPE_INDEXED:
  83855. use_pal = true;
  83856. break;
  83857. case TGATools._TYPE_RLE_RGB:
  83858. use_rle = true;
  83859. case TGATools._TYPE_RGB:
  83860. // use_rgb = true;
  83861. break;
  83862. case TGATools._TYPE_RLE_GREY:
  83863. use_rle = true;
  83864. case TGATools._TYPE_GREY:
  83865. use_grey = true;
  83866. break;
  83867. }
  83868. var pixel_data;
  83869. // var numAlphaBits = header.flags & 0xf;
  83870. var pixel_size = header.pixel_size >> 3;
  83871. var pixel_total = header.width * header.height * pixel_size;
  83872. // Read palettes
  83873. var palettes;
  83874. if (use_pal) {
  83875. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  83876. }
  83877. // Read LRE
  83878. if (use_rle) {
  83879. pixel_data = new Uint8Array(pixel_total);
  83880. var c, count, i;
  83881. var localOffset = 0;
  83882. var pixels = new Uint8Array(pixel_size);
  83883. while (offset < pixel_total && localOffset < pixel_total) {
  83884. c = data[offset++];
  83885. count = (c & 0x7f) + 1;
  83886. // RLE pixels
  83887. if (c & 0x80) {
  83888. // Bind pixel tmp array
  83889. for (i = 0; i < pixel_size; ++i) {
  83890. pixels[i] = data[offset++];
  83891. }
  83892. // Copy pixel array
  83893. for (i = 0; i < count; ++i) {
  83894. pixel_data.set(pixels, localOffset + i * pixel_size);
  83895. }
  83896. localOffset += pixel_size * count;
  83897. }
  83898. // Raw pixels
  83899. else {
  83900. count *= pixel_size;
  83901. for (i = 0; i < count; ++i) {
  83902. pixel_data[localOffset + i] = data[offset++];
  83903. }
  83904. localOffset += count;
  83905. }
  83906. }
  83907. }
  83908. // RAW Pixels
  83909. else {
  83910. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  83911. }
  83912. // Load to texture
  83913. var x_start, y_start, x_step, y_step, y_end, x_end;
  83914. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  83915. default:
  83916. case TGATools._ORIGIN_UL:
  83917. x_start = 0;
  83918. x_step = 1;
  83919. x_end = header.width;
  83920. y_start = 0;
  83921. y_step = 1;
  83922. y_end = header.height;
  83923. break;
  83924. case TGATools._ORIGIN_BL:
  83925. x_start = 0;
  83926. x_step = 1;
  83927. x_end = header.width;
  83928. y_start = header.height - 1;
  83929. y_step = -1;
  83930. y_end = -1;
  83931. break;
  83932. case TGATools._ORIGIN_UR:
  83933. x_start = header.width - 1;
  83934. x_step = -1;
  83935. x_end = -1;
  83936. y_start = 0;
  83937. y_step = 1;
  83938. y_end = header.height;
  83939. break;
  83940. case TGATools._ORIGIN_BR:
  83941. x_start = header.width - 1;
  83942. x_step = -1;
  83943. x_end = -1;
  83944. y_start = header.height - 1;
  83945. y_step = -1;
  83946. y_end = -1;
  83947. break;
  83948. }
  83949. // Load the specify method
  83950. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  83951. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  83952. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  83953. };
  83954. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83955. var image = pixel_data, colormap = palettes;
  83956. var width = header.width, height = header.height;
  83957. var color, i = 0, x, y;
  83958. var imageData = new Uint8Array(width * height * 4);
  83959. for (y = y_start; y !== y_end; y += y_step) {
  83960. for (x = x_start; x !== x_end; x += x_step, i++) {
  83961. color = image[i];
  83962. imageData[(x + width * y) * 4 + 3] = 255;
  83963. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  83964. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  83965. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  83966. }
  83967. }
  83968. return imageData;
  83969. };
  83970. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83971. var image = pixel_data;
  83972. var width = header.width, height = header.height;
  83973. var color, i = 0, x, y;
  83974. var imageData = new Uint8Array(width * height * 4);
  83975. for (y = y_start; y !== y_end; y += y_step) {
  83976. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83977. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  83978. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  83979. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  83980. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  83981. imageData[(x + width * y) * 4 + 0] = r;
  83982. imageData[(x + width * y) * 4 + 1] = g;
  83983. imageData[(x + width * y) * 4 + 2] = b;
  83984. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  83985. }
  83986. }
  83987. return imageData;
  83988. };
  83989. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83990. var image = pixel_data;
  83991. var width = header.width, height = header.height;
  83992. var i = 0, x, y;
  83993. var imageData = new Uint8Array(width * height * 4);
  83994. for (y = y_start; y !== y_end; y += y_step) {
  83995. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  83996. imageData[(x + width * y) * 4 + 3] = 255;
  83997. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83998. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83999. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84000. }
  84001. }
  84002. return imageData;
  84003. };
  84004. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84005. var image = pixel_data;
  84006. var width = header.width, height = header.height;
  84007. var i = 0, x, y;
  84008. var imageData = new Uint8Array(width * height * 4);
  84009. for (y = y_start; y !== y_end; y += y_step) {
  84010. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84011. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84012. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84013. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84014. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84015. }
  84016. }
  84017. return imageData;
  84018. };
  84019. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84020. var image = pixel_data;
  84021. var width = header.width, height = header.height;
  84022. var color, i = 0, x, y;
  84023. var imageData = new Uint8Array(width * height * 4);
  84024. for (y = y_start; y !== y_end; y += y_step) {
  84025. for (x = x_start; x !== x_end; x += x_step, i++) {
  84026. color = image[i];
  84027. imageData[(x + width * y) * 4 + 0] = color;
  84028. imageData[(x + width * y) * 4 + 1] = color;
  84029. imageData[(x + width * y) * 4 + 2] = color;
  84030. imageData[(x + width * y) * 4 + 3] = 255;
  84031. }
  84032. }
  84033. return imageData;
  84034. };
  84035. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84036. var image = pixel_data;
  84037. var width = header.width, height = header.height;
  84038. var i = 0, x, y;
  84039. var imageData = new Uint8Array(width * height * 4);
  84040. for (y = y_start; y !== y_end; y += y_step) {
  84041. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84042. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84043. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84044. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84045. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84046. }
  84047. }
  84048. return imageData;
  84049. };
  84050. //private static _TYPE_NO_DATA = 0;
  84051. TGATools._TYPE_INDEXED = 1;
  84052. TGATools._TYPE_RGB = 2;
  84053. TGATools._TYPE_GREY = 3;
  84054. TGATools._TYPE_RLE_INDEXED = 9;
  84055. TGATools._TYPE_RLE_RGB = 10;
  84056. TGATools._TYPE_RLE_GREY = 11;
  84057. TGATools._ORIGIN_MASK = 0x30;
  84058. TGATools._ORIGIN_SHIFT = 0x04;
  84059. TGATools._ORIGIN_BL = 0x00;
  84060. TGATools._ORIGIN_BR = 0x01;
  84061. TGATools._ORIGIN_UL = 0x02;
  84062. TGATools._ORIGIN_UR = 0x03;
  84063. return TGATools;
  84064. }());
  84065. BABYLON.TGATools = TGATools;
  84066. })(BABYLON || (BABYLON = {}));
  84067. //# sourceMappingURL=babylon.tga.js.map
  84068. var BABYLON;
  84069. (function (BABYLON) {
  84070. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84071. // All values and structures referenced from:
  84072. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84073. var DDS_MAGIC = 0x20534444;
  84074. var
  84075. //DDSD_CAPS = 0x1,
  84076. //DDSD_HEIGHT = 0x2,
  84077. //DDSD_WIDTH = 0x4,
  84078. //DDSD_PITCH = 0x8,
  84079. //DDSD_PIXELFORMAT = 0x1000,
  84080. DDSD_MIPMAPCOUNT = 0x20000;
  84081. //DDSD_LINEARSIZE = 0x80000,
  84082. //DDSD_DEPTH = 0x800000;
  84083. // var DDSCAPS_COMPLEX = 0x8,
  84084. // DDSCAPS_MIPMAP = 0x400000,
  84085. // DDSCAPS_TEXTURE = 0x1000;
  84086. var DDSCAPS2_CUBEMAP = 0x200;
  84087. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84088. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84089. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84090. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84091. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84092. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84093. // DDSCAPS2_VOLUME = 0x200000;
  84094. var
  84095. //DDPF_ALPHAPIXELS = 0x1,
  84096. //DDPF_ALPHA = 0x2,
  84097. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84098. //DDPF_YUV = 0x200,
  84099. DDPF_LUMINANCE = 0x20000;
  84100. function FourCCToInt32(value) {
  84101. return value.charCodeAt(0) +
  84102. (value.charCodeAt(1) << 8) +
  84103. (value.charCodeAt(2) << 16) +
  84104. (value.charCodeAt(3) << 24);
  84105. }
  84106. function Int32ToFourCC(value) {
  84107. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84108. }
  84109. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84110. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84111. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84112. var FOURCC_DX10 = FourCCToInt32("DX10");
  84113. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84114. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84115. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84116. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84117. var headerLengthInt = 31; // The header length in 32 bit ints
  84118. // Offsets into the header array
  84119. var off_magic = 0;
  84120. var off_size = 1;
  84121. var off_flags = 2;
  84122. var off_height = 3;
  84123. var off_width = 4;
  84124. var off_mipmapCount = 7;
  84125. var off_pfFlags = 20;
  84126. var off_pfFourCC = 21;
  84127. var off_RGBbpp = 22;
  84128. var off_RMask = 23;
  84129. var off_GMask = 24;
  84130. var off_BMask = 25;
  84131. var off_AMask = 26;
  84132. // var off_caps1 = 27;
  84133. var off_caps2 = 28;
  84134. // var off_caps3 = 29;
  84135. // var off_caps4 = 30;
  84136. var off_dxgiFormat = 32;
  84137. ;
  84138. var DDSTools = /** @class */ (function () {
  84139. function DDSTools() {
  84140. }
  84141. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84142. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84143. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84144. var mipmapCount = 1;
  84145. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84146. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84147. }
  84148. var fourCC = header[off_pfFourCC];
  84149. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84150. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84151. switch (fourCC) {
  84152. case FOURCC_D3DFMT_R16G16B16A16F:
  84153. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84154. break;
  84155. case FOURCC_D3DFMT_R32G32B32A32F:
  84156. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84157. break;
  84158. case FOURCC_DX10:
  84159. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84160. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84161. break;
  84162. }
  84163. }
  84164. return {
  84165. width: header[off_width],
  84166. height: header[off_height],
  84167. mipmapCount: mipmapCount,
  84168. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84169. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84170. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84171. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84172. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84173. dxgiFormat: dxgiFormat,
  84174. textureType: textureType
  84175. };
  84176. };
  84177. DDSTools._ToHalfFloat = function (value) {
  84178. if (!DDSTools._FloatView) {
  84179. DDSTools._FloatView = new Float32Array(1);
  84180. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84181. }
  84182. DDSTools._FloatView[0] = value;
  84183. var x = DDSTools._Int32View[0];
  84184. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84185. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84186. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84187. /* If zero, or denormal, or exponent underflows too much for a denormal
  84188. * half, return signed zero. */
  84189. if (e < 103) {
  84190. return bits;
  84191. }
  84192. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84193. if (e > 142) {
  84194. bits |= 0x7c00;
  84195. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84196. * not Inf, so make sure we set one mantissa bit too. */
  84197. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84198. return bits;
  84199. }
  84200. /* If exponent underflows but not too much, return a denormal */
  84201. if (e < 113) {
  84202. m |= 0x0800;
  84203. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84204. * to 1, which is OK. */
  84205. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84206. return bits;
  84207. }
  84208. bits |= ((e - 112) << 10) | (m >> 1);
  84209. bits += m & 1;
  84210. return bits;
  84211. };
  84212. DDSTools._FromHalfFloat = function (value) {
  84213. var s = (value & 0x8000) >> 15;
  84214. var e = (value & 0x7C00) >> 10;
  84215. var f = value & 0x03FF;
  84216. if (e === 0) {
  84217. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84218. }
  84219. else if (e == 0x1F) {
  84220. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84221. }
  84222. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84223. };
  84224. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84225. var destArray = new Float32Array(dataLength);
  84226. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84227. var index = 0;
  84228. for (var y = 0; y < height; y++) {
  84229. for (var x = 0; x < width; x++) {
  84230. var srcPos = (x + y * width) * 4;
  84231. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84232. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84233. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84234. if (DDSTools.StoreLODInAlphaChannel) {
  84235. destArray[index + 3] = lod;
  84236. }
  84237. else {
  84238. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84239. }
  84240. index += 4;
  84241. }
  84242. }
  84243. return destArray;
  84244. };
  84245. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84246. if (DDSTools.StoreLODInAlphaChannel) {
  84247. var destArray = new Uint16Array(dataLength);
  84248. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84249. var index = 0;
  84250. for (var y = 0; y < height; y++) {
  84251. for (var x = 0; x < width; x++) {
  84252. var srcPos = (x + y * width) * 4;
  84253. destArray[index] = srcData[srcPos];
  84254. destArray[index + 1] = srcData[srcPos + 1];
  84255. destArray[index + 2] = srcData[srcPos + 2];
  84256. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84257. index += 4;
  84258. }
  84259. }
  84260. return destArray;
  84261. }
  84262. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84263. };
  84264. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84265. if (DDSTools.StoreLODInAlphaChannel) {
  84266. var destArray = new Float32Array(dataLength);
  84267. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84268. var index = 0;
  84269. for (var y = 0; y < height; y++) {
  84270. for (var x = 0; x < width; x++) {
  84271. var srcPos = (x + y * width) * 4;
  84272. destArray[index] = srcData[srcPos];
  84273. destArray[index + 1] = srcData[srcPos + 1];
  84274. destArray[index + 2] = srcData[srcPos + 2];
  84275. destArray[index + 3] = lod;
  84276. index += 4;
  84277. }
  84278. }
  84279. return destArray;
  84280. }
  84281. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84282. };
  84283. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84284. var destArray = new Uint8Array(dataLength);
  84285. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84286. var index = 0;
  84287. for (var y = 0; y < height; y++) {
  84288. for (var x = 0; x < width; x++) {
  84289. var srcPos = (x + y * width) * 4;
  84290. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84291. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84292. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84293. if (DDSTools.StoreLODInAlphaChannel) {
  84294. destArray[index + 3] = lod;
  84295. }
  84296. else {
  84297. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84298. }
  84299. index += 4;
  84300. }
  84301. }
  84302. return destArray;
  84303. };
  84304. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84305. var destArray = new Uint8Array(dataLength);
  84306. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84307. var index = 0;
  84308. for (var y = 0; y < height; y++) {
  84309. for (var x = 0; x < width; x++) {
  84310. var srcPos = (x + y * width) * 4;
  84311. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84312. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84313. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84314. if (DDSTools.StoreLODInAlphaChannel) {
  84315. destArray[index + 3] = lod;
  84316. }
  84317. else {
  84318. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84319. }
  84320. index += 4;
  84321. }
  84322. }
  84323. return destArray;
  84324. };
  84325. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84326. var byteArray = new Uint8Array(dataLength);
  84327. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84328. var index = 0;
  84329. for (var y = 0; y < height; y++) {
  84330. for (var x = 0; x < width; x++) {
  84331. var srcPos = (x + y * width) * 4;
  84332. byteArray[index] = srcData[srcPos + rOffset];
  84333. byteArray[index + 1] = srcData[srcPos + gOffset];
  84334. byteArray[index + 2] = srcData[srcPos + bOffset];
  84335. byteArray[index + 3] = srcData[srcPos + aOffset];
  84336. index += 4;
  84337. }
  84338. }
  84339. return byteArray;
  84340. };
  84341. DDSTools._ExtractLongWordOrder = function (value) {
  84342. if (value === 0 || value === 255 || value === -16777216) {
  84343. return 0;
  84344. }
  84345. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84346. };
  84347. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84348. var byteArray = new Uint8Array(dataLength);
  84349. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84350. var index = 0;
  84351. for (var y = 0; y < height; y++) {
  84352. for (var x = 0; x < width; x++) {
  84353. var srcPos = (x + y * width) * 3;
  84354. byteArray[index] = srcData[srcPos + rOffset];
  84355. byteArray[index + 1] = srcData[srcPos + gOffset];
  84356. byteArray[index + 2] = srcData[srcPos + bOffset];
  84357. index += 3;
  84358. }
  84359. }
  84360. return byteArray;
  84361. };
  84362. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84363. var byteArray = new Uint8Array(dataLength);
  84364. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84365. var index = 0;
  84366. for (var y = 0; y < height; y++) {
  84367. for (var x = 0; x < width; x++) {
  84368. var srcPos = (x + y * width);
  84369. byteArray[index] = srcData[srcPos];
  84370. index++;
  84371. }
  84372. }
  84373. return byteArray;
  84374. };
  84375. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84376. if (lodIndex === void 0) { lodIndex = -1; }
  84377. var sphericalPolynomialFaces = null;
  84378. if (info.sphericalPolynomial) {
  84379. sphericalPolynomialFaces = new Array();
  84380. }
  84381. var ext = engine.getCaps().s3tc;
  84382. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84383. var fourCC, width, height, dataLength = 0, dataOffset;
  84384. var byteArray, mipmapCount, mip;
  84385. var internalFormat = 0;
  84386. var format = 0;
  84387. var blockBytes = 1;
  84388. if (header[off_magic] !== DDS_MAGIC) {
  84389. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84390. return;
  84391. }
  84392. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84393. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84394. return;
  84395. }
  84396. if (info.isCompressed && !ext) {
  84397. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84398. return;
  84399. }
  84400. var bpp = header[off_RGBbpp];
  84401. dataOffset = header[off_size] + 4;
  84402. var computeFormats = false;
  84403. if (info.isFourCC) {
  84404. fourCC = header[off_pfFourCC];
  84405. switch (fourCC) {
  84406. case FOURCC_DXT1:
  84407. blockBytes = 8;
  84408. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84409. break;
  84410. case FOURCC_DXT3:
  84411. blockBytes = 16;
  84412. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84413. break;
  84414. case FOURCC_DXT5:
  84415. blockBytes = 16;
  84416. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84417. break;
  84418. case FOURCC_D3DFMT_R16G16B16A16F:
  84419. computeFormats = true;
  84420. break;
  84421. case FOURCC_D3DFMT_R32G32B32A32F:
  84422. computeFormats = true;
  84423. break;
  84424. case FOURCC_DX10:
  84425. // There is an additionnal header so dataOffset need to be changed
  84426. dataOffset += 5 * 4; // 5 uints
  84427. var supported = false;
  84428. switch (info.dxgiFormat) {
  84429. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84430. computeFormats = true;
  84431. supported = true;
  84432. break;
  84433. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84434. info.isRGB = true;
  84435. info.isFourCC = false;
  84436. bpp = 32;
  84437. supported = true;
  84438. break;
  84439. }
  84440. if (supported) {
  84441. break;
  84442. }
  84443. default:
  84444. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84445. return;
  84446. }
  84447. }
  84448. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84449. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84450. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84451. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84452. if (computeFormats) {
  84453. format = engine._getWebGLTextureType(info.textureType);
  84454. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84455. }
  84456. mipmapCount = 1;
  84457. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84458. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84459. }
  84460. for (var face = 0; face < faces; face++) {
  84461. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84462. width = header[off_width];
  84463. height = header[off_height];
  84464. for (mip = 0; mip < mipmapCount; ++mip) {
  84465. if (lodIndex === -1 || lodIndex === mip) {
  84466. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84467. var i = (lodIndex === -1) ? mip : 0;
  84468. if (!info.isCompressed && info.isFourCC) {
  84469. dataLength = width * height * 4;
  84470. var floatArray = null;
  84471. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84472. if (bpp === 128) {
  84473. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84474. if (sphericalPolynomialFaces && i == 0) {
  84475. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84476. }
  84477. }
  84478. else if (bpp === 64) {
  84479. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84480. if (sphericalPolynomialFaces && i == 0) {
  84481. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84482. }
  84483. }
  84484. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84485. format = engine._getWebGLTextureType(info.textureType);
  84486. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84487. }
  84488. else {
  84489. if (bpp === 128) {
  84490. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84491. if (sphericalPolynomialFaces && i == 0) {
  84492. sphericalPolynomialFaces.push(floatArray);
  84493. }
  84494. }
  84495. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84496. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84497. if (sphericalPolynomialFaces && i == 0) {
  84498. sphericalPolynomialFaces.push(floatArray);
  84499. }
  84500. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84501. format = engine._getWebGLTextureType(info.textureType);
  84502. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84503. }
  84504. else { // 64
  84505. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84506. if (sphericalPolynomialFaces && i == 0) {
  84507. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84508. }
  84509. }
  84510. }
  84511. if (floatArray) {
  84512. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84513. }
  84514. }
  84515. else if (info.isRGB) {
  84516. if (bpp === 24) {
  84517. dataLength = width * height * 3;
  84518. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84519. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84520. }
  84521. else { // 32
  84522. dataLength = width * height * 4;
  84523. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84524. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84525. }
  84526. }
  84527. else if (info.isLuminance) {
  84528. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84529. var unpaddedRowSize = width;
  84530. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84531. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84532. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84533. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84534. }
  84535. else {
  84536. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84537. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84538. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84539. }
  84540. }
  84541. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84542. width *= 0.5;
  84543. height *= 0.5;
  84544. width = Math.max(1.0, width);
  84545. height = Math.max(1.0, height);
  84546. }
  84547. if (currentFace !== undefined) {
  84548. // Loading a single face
  84549. break;
  84550. }
  84551. }
  84552. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84553. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84554. size: header[off_width],
  84555. right: sphericalPolynomialFaces[0],
  84556. left: sphericalPolynomialFaces[1],
  84557. up: sphericalPolynomialFaces[2],
  84558. down: sphericalPolynomialFaces[3],
  84559. front: sphericalPolynomialFaces[4],
  84560. back: sphericalPolynomialFaces[5],
  84561. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84562. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84563. gammaSpace: false,
  84564. });
  84565. }
  84566. else {
  84567. info.sphericalPolynomial = undefined;
  84568. }
  84569. };
  84570. DDSTools.StoreLODInAlphaChannel = false;
  84571. return DDSTools;
  84572. }());
  84573. BABYLON.DDSTools = DDSTools;
  84574. })(BABYLON || (BABYLON = {}));
  84575. //# sourceMappingURL=babylon.dds.js.map
  84576. var BABYLON;
  84577. (function (BABYLON) {
  84578. /**
  84579. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84580. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84581. */
  84582. var KhronosTextureContainer = /** @class */ (function () {
  84583. /**
  84584. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84585. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84586. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84587. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84588. */
  84589. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84590. this.arrayBuffer = arrayBuffer;
  84591. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84592. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84593. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84594. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84595. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84596. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84597. BABYLON.Tools.Error("texture missing KTX identifier");
  84598. return;
  84599. }
  84600. // load the reset of the header in native 32 bit int
  84601. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84602. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84603. var oppositeEndianess = header[0] === 0x01020304;
  84604. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84605. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84606. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84607. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84608. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84609. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84610. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84611. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84612. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84613. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84614. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84615. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84616. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84617. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84618. if (this.glType !== 0) {
  84619. BABYLON.Tools.Error("only compressed formats currently supported");
  84620. return;
  84621. }
  84622. else {
  84623. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84624. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84625. }
  84626. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84627. BABYLON.Tools.Error("only 2D textures currently supported");
  84628. return;
  84629. }
  84630. if (this.numberOfArrayElements !== 0) {
  84631. BABYLON.Tools.Error("texture arrays not currently supported");
  84632. return;
  84633. }
  84634. if (this.numberOfFaces !== facesExpected) {
  84635. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84636. return;
  84637. }
  84638. // we now have a completely validated file, so could use existence of loadType as success
  84639. // would need to make this more elaborate & adjust checks above to support more than one load type
  84640. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84641. }
  84642. // not as fast hardware based, but will probably never need to use
  84643. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84644. return ((val & 0xFF) << 24)
  84645. | ((val & 0xFF00) << 8)
  84646. | ((val >> 8) & 0xFF00)
  84647. | ((val >> 24) & 0xFF);
  84648. };
  84649. /**
  84650. * It is assumed that the texture has already been created & is currently bound
  84651. */
  84652. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84653. switch (this.loadType) {
  84654. case KhronosTextureContainer.COMPRESSED_2D:
  84655. this._upload2DCompressedLevels(gl, loadMipmaps);
  84656. break;
  84657. case KhronosTextureContainer.TEX_2D:
  84658. case KhronosTextureContainer.COMPRESSED_3D:
  84659. case KhronosTextureContainer.TEX_3D:
  84660. }
  84661. };
  84662. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84663. // initialize width & height for level 1
  84664. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84665. var width = this.pixelWidth;
  84666. var height = this.pixelHeight;
  84667. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84668. for (var level = 0; level < mipmapCount; level++) {
  84669. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84670. for (var face = 0; face < this.numberOfFaces; face++) {
  84671. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84672. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84673. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84674. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84675. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84676. }
  84677. width = Math.max(1.0, width * 0.5);
  84678. height = Math.max(1.0, height * 0.5);
  84679. }
  84680. };
  84681. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84682. // load types
  84683. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84684. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84685. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84686. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84687. return KhronosTextureContainer;
  84688. }());
  84689. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84690. })(BABYLON || (BABYLON = {}));
  84691. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84692. var BABYLON;
  84693. (function (BABYLON) {
  84694. var Debug;
  84695. (function (Debug) {
  84696. /**
  84697. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84698. */
  84699. var SkeletonViewer = /** @class */ (function () {
  84700. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84701. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84702. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84703. this.skeleton = skeleton;
  84704. this.mesh = mesh;
  84705. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84706. this.renderingGroupId = renderingGroupId;
  84707. this.color = BABYLON.Color3.White();
  84708. this._debugLines = new Array();
  84709. this._isEnabled = false;
  84710. this._scene = scene;
  84711. this.update();
  84712. this._renderFunction = this.update.bind(this);
  84713. }
  84714. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84715. get: function () {
  84716. return this._isEnabled;
  84717. },
  84718. set: function (value) {
  84719. if (this._isEnabled === value) {
  84720. return;
  84721. }
  84722. this._isEnabled = value;
  84723. if (value) {
  84724. this._scene.registerBeforeRender(this._renderFunction);
  84725. }
  84726. else {
  84727. this._scene.unregisterBeforeRender(this._renderFunction);
  84728. }
  84729. },
  84730. enumerable: true,
  84731. configurable: true
  84732. });
  84733. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84734. if (x === void 0) { x = 0; }
  84735. if (y === void 0) { y = 0; }
  84736. if (z === void 0) { z = 0; }
  84737. var tmat = BABYLON.Tmp.Matrix[0];
  84738. var parentBone = bone.getParent();
  84739. tmat.copyFrom(bone.getLocalMatrix());
  84740. if (x !== 0 || y !== 0 || z !== 0) {
  84741. var tmat2 = BABYLON.Tmp.Matrix[1];
  84742. BABYLON.Matrix.IdentityToRef(tmat2);
  84743. tmat2.m[12] = x;
  84744. tmat2.m[13] = y;
  84745. tmat2.m[14] = z;
  84746. tmat2.multiplyToRef(tmat, tmat);
  84747. }
  84748. if (parentBone) {
  84749. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84750. }
  84751. tmat.multiplyToRef(meshMat, tmat);
  84752. position.x = tmat.m[12];
  84753. position.y = tmat.m[13];
  84754. position.z = tmat.m[14];
  84755. };
  84756. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84757. var len = bones.length;
  84758. var meshPos = this.mesh.position;
  84759. for (var i = 0; i < len; i++) {
  84760. var bone = bones[i];
  84761. var points = this._debugLines[i];
  84762. if (!points) {
  84763. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84764. this._debugLines[i] = points;
  84765. }
  84766. this._getBonePosition(points[0], bone, meshMat);
  84767. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84768. points[0].subtractInPlace(meshPos);
  84769. points[1].subtractInPlace(meshPos);
  84770. }
  84771. };
  84772. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84773. var len = bones.length;
  84774. var boneNum = 0;
  84775. var meshPos = this.mesh.position;
  84776. for (var i = len - 1; i >= 0; i--) {
  84777. var childBone = bones[i];
  84778. var parentBone = childBone.getParent();
  84779. if (!parentBone) {
  84780. continue;
  84781. }
  84782. var points = this._debugLines[boneNum];
  84783. if (!points) {
  84784. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84785. this._debugLines[boneNum] = points;
  84786. }
  84787. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84788. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84789. points[0].subtractInPlace(meshPos);
  84790. points[1].subtractInPlace(meshPos);
  84791. boneNum++;
  84792. }
  84793. };
  84794. SkeletonViewer.prototype.update = function () {
  84795. if (this.autoUpdateBonesMatrices) {
  84796. this.skeleton.computeAbsoluteTransforms();
  84797. }
  84798. if (this.skeleton.bones[0].length === undefined) {
  84799. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84800. }
  84801. else {
  84802. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84803. }
  84804. if (!this._debugMesh) {
  84805. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84806. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84807. }
  84808. else {
  84809. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84810. }
  84811. this._debugMesh.position.copyFrom(this.mesh.position);
  84812. this._debugMesh.color = this.color;
  84813. };
  84814. SkeletonViewer.prototype.dispose = function () {
  84815. if (this._debugMesh) {
  84816. this.isEnabled = false;
  84817. this._debugMesh.dispose();
  84818. this._debugMesh = null;
  84819. }
  84820. };
  84821. return SkeletonViewer;
  84822. }());
  84823. Debug.SkeletonViewer = SkeletonViewer;
  84824. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84825. })(BABYLON || (BABYLON = {}));
  84826. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84827. /**
  84828. * Module Debug contains the (visual) components to debug a scene correctly
  84829. */
  84830. var BABYLON;
  84831. (function (BABYLON) {
  84832. var Debug;
  84833. (function (Debug) {
  84834. /**
  84835. * The Axes viewer will show 3 axes in a specific point in space
  84836. */
  84837. var AxesViewer = /** @class */ (function () {
  84838. function AxesViewer(scene, scaleLines) {
  84839. if (scaleLines === void 0) { scaleLines = 1; }
  84840. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84841. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84842. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84843. this.scaleLines = 1;
  84844. this.scaleLines = scaleLines;
  84845. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84846. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84847. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84848. this._xmesh.renderingGroupId = 2;
  84849. this._ymesh.renderingGroupId = 2;
  84850. this._zmesh.renderingGroupId = 2;
  84851. this._xmesh.material.checkReadyOnlyOnce = true;
  84852. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84853. this._ymesh.material.checkReadyOnlyOnce = true;
  84854. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84855. this._zmesh.material.checkReadyOnlyOnce = true;
  84856. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84857. this.scene = scene;
  84858. }
  84859. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84860. var scaleLines = this.scaleLines;
  84861. if (this._xmesh) {
  84862. this._xmesh.position.copyFrom(position);
  84863. }
  84864. if (this._ymesh) {
  84865. this._ymesh.position.copyFrom(position);
  84866. }
  84867. if (this._zmesh) {
  84868. this._zmesh.position.copyFrom(position);
  84869. }
  84870. var point2 = this._xline[1];
  84871. point2.x = xaxis.x * scaleLines;
  84872. point2.y = xaxis.y * scaleLines;
  84873. point2.z = xaxis.z * scaleLines;
  84874. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84875. point2 = this._yline[1];
  84876. point2.x = yaxis.x * scaleLines;
  84877. point2.y = yaxis.y * scaleLines;
  84878. point2.z = yaxis.z * scaleLines;
  84879. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  84880. point2 = this._zline[1];
  84881. point2.x = zaxis.x * scaleLines;
  84882. point2.y = zaxis.y * scaleLines;
  84883. point2.z = zaxis.z * scaleLines;
  84884. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  84885. };
  84886. AxesViewer.prototype.dispose = function () {
  84887. if (this._xmesh) {
  84888. this._xmesh.dispose();
  84889. }
  84890. if (this._ymesh) {
  84891. this._ymesh.dispose();
  84892. }
  84893. if (this._zmesh) {
  84894. this._zmesh.dispose();
  84895. }
  84896. this._xmesh = null;
  84897. this._ymesh = null;
  84898. this._zmesh = null;
  84899. this.scene = null;
  84900. };
  84901. return AxesViewer;
  84902. }());
  84903. Debug.AxesViewer = AxesViewer;
  84904. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84905. })(BABYLON || (BABYLON = {}));
  84906. //# sourceMappingURL=babylon.axesViewer.js.map
  84907. var BABYLON;
  84908. (function (BABYLON) {
  84909. var Debug;
  84910. (function (Debug) {
  84911. /**
  84912. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  84913. */
  84914. var BoneAxesViewer = /** @class */ (function (_super) {
  84915. __extends(BoneAxesViewer, _super);
  84916. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  84917. if (scaleLines === void 0) { scaleLines = 1; }
  84918. var _this = _super.call(this, scene, scaleLines) || this;
  84919. _this.pos = BABYLON.Vector3.Zero();
  84920. _this.xaxis = BABYLON.Vector3.Zero();
  84921. _this.yaxis = BABYLON.Vector3.Zero();
  84922. _this.zaxis = BABYLON.Vector3.Zero();
  84923. _this.mesh = mesh;
  84924. _this.bone = bone;
  84925. return _this;
  84926. }
  84927. BoneAxesViewer.prototype.update = function () {
  84928. if (!this.mesh || !this.bone) {
  84929. return;
  84930. }
  84931. var bone = this.bone;
  84932. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  84933. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  84934. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  84935. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  84936. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  84937. };
  84938. BoneAxesViewer.prototype.dispose = function () {
  84939. if (this.mesh) {
  84940. this.mesh = null;
  84941. this.bone = null;
  84942. _super.prototype.dispose.call(this);
  84943. }
  84944. };
  84945. return BoneAxesViewer;
  84946. }(Debug.AxesViewer));
  84947. Debug.BoneAxesViewer = BoneAxesViewer;
  84948. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84949. })(BABYLON || (BABYLON = {}));
  84950. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  84951. var BABYLON;
  84952. (function (BABYLON) {
  84953. var RayHelper = /** @class */ (function () {
  84954. function RayHelper(ray) {
  84955. this.ray = ray;
  84956. }
  84957. RayHelper.CreateAndShow = function (ray, scene, color) {
  84958. var helper = new RayHelper(ray);
  84959. helper.show(scene, color);
  84960. return helper;
  84961. };
  84962. RayHelper.prototype.show = function (scene, color) {
  84963. if (!this._renderFunction && this.ray) {
  84964. var ray = this.ray;
  84965. this._renderFunction = this._render.bind(this);
  84966. this._scene = scene;
  84967. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  84968. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  84969. if (this._renderFunction) {
  84970. this._scene.registerBeforeRender(this._renderFunction);
  84971. }
  84972. }
  84973. if (color && this._renderLine) {
  84974. this._renderLine.color.copyFrom(color);
  84975. }
  84976. };
  84977. RayHelper.prototype.hide = function () {
  84978. if (this._renderFunction && this._scene) {
  84979. this._scene.unregisterBeforeRender(this._renderFunction);
  84980. this._scene = null;
  84981. this._renderFunction = null;
  84982. if (this._renderLine) {
  84983. this._renderLine.dispose();
  84984. this._renderLine = null;
  84985. }
  84986. this._renderPoints = [];
  84987. }
  84988. };
  84989. RayHelper.prototype._render = function () {
  84990. var ray = this.ray;
  84991. if (!ray) {
  84992. return;
  84993. }
  84994. var point = this._renderPoints[1];
  84995. var len = Math.min(ray.length, 1000000);
  84996. point.copyFrom(ray.direction);
  84997. point.scaleInPlace(len);
  84998. point.addInPlace(ray.origin);
  84999. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85000. };
  85001. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85002. this._attachedToMesh = mesh;
  85003. var ray = this.ray;
  85004. if (!ray) {
  85005. return;
  85006. }
  85007. if (!ray.direction) {
  85008. ray.direction = BABYLON.Vector3.Zero();
  85009. }
  85010. if (!ray.origin) {
  85011. ray.origin = BABYLON.Vector3.Zero();
  85012. }
  85013. if (length) {
  85014. ray.length = length;
  85015. }
  85016. if (!meshSpaceOrigin) {
  85017. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85018. }
  85019. if (!meshSpaceDirection) {
  85020. // -1 so that this will work with Mesh.lookAt
  85021. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85022. }
  85023. if (!this._meshSpaceDirection) {
  85024. this._meshSpaceDirection = meshSpaceDirection.clone();
  85025. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85026. }
  85027. else {
  85028. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85029. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85030. }
  85031. if (!this._updateToMeshFunction) {
  85032. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85033. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85034. }
  85035. this._updateToMesh();
  85036. };
  85037. RayHelper.prototype.detachFromMesh = function () {
  85038. if (this._attachedToMesh) {
  85039. if (this._updateToMeshFunction) {
  85040. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85041. }
  85042. this._attachedToMesh = null;
  85043. this._updateToMeshFunction = null;
  85044. }
  85045. };
  85046. RayHelper.prototype._updateToMesh = function () {
  85047. var ray = this.ray;
  85048. if (!this._attachedToMesh || !ray) {
  85049. return;
  85050. }
  85051. if (this._attachedToMesh._isDisposed) {
  85052. this.detachFromMesh();
  85053. return;
  85054. }
  85055. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85056. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85057. };
  85058. RayHelper.prototype.dispose = function () {
  85059. this.hide();
  85060. this.detachFromMesh();
  85061. this.ray = null;
  85062. };
  85063. return RayHelper;
  85064. }());
  85065. BABYLON.RayHelper = RayHelper;
  85066. })(BABYLON || (BABYLON = {}));
  85067. //# sourceMappingURL=babylon.rayHelper.js.map
  85068. var BABYLON;
  85069. (function (BABYLON) {
  85070. // load the inspector using require, if not present in the global namespace.
  85071. var DebugLayer = /** @class */ (function () {
  85072. function DebugLayer(scene) {
  85073. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85074. this._scene = scene;
  85075. // load inspector using require, if it doesn't exist on the global namespace.
  85076. }
  85077. /** Creates the inspector window. */
  85078. DebugLayer.prototype._createInspector = function (config) {
  85079. if (config === void 0) { config = {}; }
  85080. var popup = config.popup || false;
  85081. var initialTab = config.initialTab || 0;
  85082. var parentElement = config.parentElement || null;
  85083. if (!this._inspector) {
  85084. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85085. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85086. } // else nothing to do,; instance is already existing
  85087. };
  85088. DebugLayer.prototype.isVisible = function () {
  85089. if (!this._inspector) {
  85090. return false;
  85091. }
  85092. return true;
  85093. };
  85094. DebugLayer.prototype.hide = function () {
  85095. if (this._inspector) {
  85096. try {
  85097. this._inspector.dispose();
  85098. }
  85099. catch (e) {
  85100. // If the inspector has been removed directly from the inspector tool
  85101. }
  85102. this._inspector = null;
  85103. }
  85104. };
  85105. DebugLayer.prototype.show = function (config) {
  85106. if (config === void 0) { config = {}; }
  85107. if (typeof this.BJSINSPECTOR == 'undefined') {
  85108. // Load inspector and add it to the DOM
  85109. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85110. }
  85111. else {
  85112. // Otherwise creates the inspector
  85113. this._createInspector(config);
  85114. }
  85115. };
  85116. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85117. return DebugLayer;
  85118. }());
  85119. BABYLON.DebugLayer = DebugLayer;
  85120. })(BABYLON || (BABYLON = {}));
  85121. //# sourceMappingURL=babylon.debugLayer.js.map
  85122. var BABYLON;
  85123. (function (BABYLON) {
  85124. var Debug;
  85125. (function (Debug) {
  85126. /**
  85127. * Used to show the physics impostor around the specific mesh.
  85128. */
  85129. var PhysicsViewer = /** @class */ (function () {
  85130. function PhysicsViewer(scene) {
  85131. this._impostors = [];
  85132. this._meshes = [];
  85133. this._numMeshes = 0;
  85134. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85135. var physicEngine = this._scene.getPhysicsEngine();
  85136. if (physicEngine) {
  85137. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85138. }
  85139. }
  85140. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85141. var plugin = this._physicsEnginePlugin;
  85142. for (var i = 0; i < this._numMeshes; i++) {
  85143. var impostor = this._impostors[i];
  85144. if (!impostor) {
  85145. continue;
  85146. }
  85147. if (impostor.isDisposed) {
  85148. this.hideImpostor(this._impostors[i--]);
  85149. }
  85150. else {
  85151. var mesh = this._meshes[i];
  85152. if (mesh && plugin) {
  85153. plugin.syncMeshWithImpostor(mesh, impostor);
  85154. }
  85155. }
  85156. }
  85157. };
  85158. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85159. if (!this._scene) {
  85160. return;
  85161. }
  85162. for (var i = 0; i < this._numMeshes; i++) {
  85163. if (this._impostors[i] == impostor) {
  85164. return;
  85165. }
  85166. }
  85167. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85168. if (debugMesh) {
  85169. this._impostors[this._numMeshes] = impostor;
  85170. this._meshes[this._numMeshes] = debugMesh;
  85171. if (this._numMeshes === 0) {
  85172. this._renderFunction = this._updateDebugMeshes.bind(this);
  85173. this._scene.registerBeforeRender(this._renderFunction);
  85174. }
  85175. this._numMeshes++;
  85176. }
  85177. };
  85178. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85179. if (!impostor || !this._scene) {
  85180. return;
  85181. }
  85182. var removed = false;
  85183. for (var i = 0; i < this._numMeshes; i++) {
  85184. if (this._impostors[i] == impostor) {
  85185. var mesh = this._meshes[i];
  85186. if (!mesh) {
  85187. continue;
  85188. }
  85189. this._scene.removeMesh(mesh);
  85190. mesh.dispose();
  85191. this._numMeshes--;
  85192. if (this._numMeshes > 0) {
  85193. this._meshes[i] = this._meshes[this._numMeshes];
  85194. this._impostors[i] = this._impostors[this._numMeshes];
  85195. this._meshes[this._numMeshes] = null;
  85196. this._impostors[this._numMeshes] = null;
  85197. }
  85198. else {
  85199. this._meshes[0] = null;
  85200. this._impostors[0] = null;
  85201. }
  85202. removed = true;
  85203. break;
  85204. }
  85205. }
  85206. if (removed && this._numMeshes === 0) {
  85207. this._scene.unregisterBeforeRender(this._renderFunction);
  85208. }
  85209. };
  85210. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85211. if (!this._debugMaterial) {
  85212. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85213. this._debugMaterial.wireframe = true;
  85214. }
  85215. return this._debugMaterial;
  85216. };
  85217. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85218. if (!this._debugBoxMesh) {
  85219. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85220. this._debugBoxMesh.renderingGroupId = 1;
  85221. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85222. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85223. scene.removeMesh(this._debugBoxMesh);
  85224. }
  85225. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85226. };
  85227. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85228. if (!this._debugSphereMesh) {
  85229. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85230. this._debugSphereMesh.renderingGroupId = 1;
  85231. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85232. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85233. scene.removeMesh(this._debugSphereMesh);
  85234. }
  85235. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85236. };
  85237. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85238. var mesh = null;
  85239. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85240. mesh = this._getDebugBoxMesh(scene);
  85241. impostor.getBoxSizeToRef(mesh.scaling);
  85242. }
  85243. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85244. mesh = this._getDebugSphereMesh(scene);
  85245. var radius = impostor.getRadius();
  85246. mesh.scaling.x = radius * 2;
  85247. mesh.scaling.y = radius * 2;
  85248. mesh.scaling.z = radius * 2;
  85249. }
  85250. return mesh;
  85251. };
  85252. PhysicsViewer.prototype.dispose = function () {
  85253. for (var i = 0; i < this._numMeshes; i++) {
  85254. this.hideImpostor(this._impostors[i]);
  85255. }
  85256. if (this._debugBoxMesh) {
  85257. this._debugBoxMesh.dispose();
  85258. }
  85259. if (this._debugSphereMesh) {
  85260. this._debugSphereMesh.dispose();
  85261. }
  85262. if (this._debugMaterial) {
  85263. this._debugMaterial.dispose();
  85264. }
  85265. this._impostors.length = 0;
  85266. this._scene = null;
  85267. this._physicsEnginePlugin = null;
  85268. };
  85269. return PhysicsViewer;
  85270. }());
  85271. Debug.PhysicsViewer = PhysicsViewer;
  85272. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85273. })(BABYLON || (BABYLON = {}));
  85274. //# sourceMappingURL=babylon.physicsViewer.js.map
  85275. var BABYLON;
  85276. (function (BABYLON) {
  85277. var BoundingBoxRenderer = /** @class */ (function () {
  85278. function BoundingBoxRenderer(scene) {
  85279. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85280. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85281. this.showBackLines = true;
  85282. this.renderList = new BABYLON.SmartArray(32);
  85283. this._vertexBuffers = {};
  85284. this._scene = scene;
  85285. }
  85286. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85287. if (this._colorShader) {
  85288. return;
  85289. }
  85290. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85291. attributes: [BABYLON.VertexBuffer.PositionKind],
  85292. uniforms: ["world", "viewProjection", "color"]
  85293. });
  85294. var engine = this._scene.getEngine();
  85295. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85296. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85297. this._createIndexBuffer();
  85298. };
  85299. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85300. var engine = this._scene.getEngine();
  85301. 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]);
  85302. };
  85303. BoundingBoxRenderer.prototype._rebuild = function () {
  85304. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85305. if (vb) {
  85306. vb._rebuild();
  85307. }
  85308. this._createIndexBuffer();
  85309. };
  85310. BoundingBoxRenderer.prototype.reset = function () {
  85311. this.renderList.reset();
  85312. };
  85313. BoundingBoxRenderer.prototype.render = function () {
  85314. if (this.renderList.length === 0) {
  85315. return;
  85316. }
  85317. this._prepareRessources();
  85318. if (!this._colorShader.isReady()) {
  85319. return;
  85320. }
  85321. var engine = this._scene.getEngine();
  85322. engine.setDepthWrite(false);
  85323. this._colorShader._preBind();
  85324. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85325. var boundingBox = this.renderList.data[boundingBoxIndex];
  85326. var min = boundingBox.minimum;
  85327. var max = boundingBox.maximum;
  85328. var diff = max.subtract(min);
  85329. var median = min.add(diff.scale(0.5));
  85330. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85331. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85332. .multiply(boundingBox.getWorldMatrix());
  85333. // VBOs
  85334. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85335. if (this.showBackLines) {
  85336. // Back
  85337. engine.setDepthFunctionToGreaterOrEqual();
  85338. this._scene.resetCachedMaterial();
  85339. this._colorShader.setColor4("color", this.backColor.toColor4());
  85340. this._colorShader.bind(worldMatrix);
  85341. // Draw order
  85342. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85343. }
  85344. // Front
  85345. engine.setDepthFunctionToLess();
  85346. this._scene.resetCachedMaterial();
  85347. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85348. this._colorShader.bind(worldMatrix);
  85349. // Draw order
  85350. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85351. }
  85352. this._colorShader.unbind();
  85353. engine.setDepthFunctionToLessOrEqual();
  85354. engine.setDepthWrite(true);
  85355. };
  85356. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85357. this._prepareRessources();
  85358. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85359. return;
  85360. }
  85361. var engine = this._scene.getEngine();
  85362. engine.setDepthWrite(false);
  85363. engine.setColorWrite(false);
  85364. this._colorShader._preBind();
  85365. var boundingBox = mesh._boundingInfo.boundingBox;
  85366. var min = boundingBox.minimum;
  85367. var max = boundingBox.maximum;
  85368. var diff = max.subtract(min);
  85369. var median = min.add(diff.scale(0.5));
  85370. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85371. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85372. .multiply(boundingBox.getWorldMatrix());
  85373. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85374. engine.setDepthFunctionToLess();
  85375. this._scene.resetCachedMaterial();
  85376. this._colorShader.bind(worldMatrix);
  85377. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85378. this._colorShader.unbind();
  85379. engine.setDepthFunctionToLessOrEqual();
  85380. engine.setDepthWrite(true);
  85381. engine.setColorWrite(true);
  85382. };
  85383. BoundingBoxRenderer.prototype.dispose = function () {
  85384. if (!this._colorShader) {
  85385. return;
  85386. }
  85387. this.renderList.dispose();
  85388. this._colorShader.dispose();
  85389. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85390. if (buffer) {
  85391. buffer.dispose();
  85392. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85393. }
  85394. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85395. };
  85396. return BoundingBoxRenderer;
  85397. }());
  85398. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85399. })(BABYLON || (BABYLON = {}));
  85400. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85401. var BABYLON;
  85402. (function (BABYLON) {
  85403. /**
  85404. * Defines a target to use with MorphTargetManager
  85405. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85406. */
  85407. var MorphTarget = /** @class */ (function () {
  85408. /**
  85409. * Creates a new MorphTarget
  85410. * @param name defines the name of the target
  85411. * @param influence defines the influence to use
  85412. */
  85413. function MorphTarget(
  85414. /** defines the name of the target */
  85415. name, influence, scene) {
  85416. if (influence === void 0) { influence = 0; }
  85417. if (scene === void 0) { scene = null; }
  85418. this.name = name;
  85419. /**
  85420. * Gets or sets the list of animations
  85421. */
  85422. this.animations = new Array();
  85423. this._positions = null;
  85424. this._normals = null;
  85425. this._tangents = null;
  85426. /**
  85427. * Observable raised when the influence changes
  85428. */
  85429. this.onInfluenceChanged = new BABYLON.Observable();
  85430. this._animationPropertiesOverride = null;
  85431. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85432. this.influence = influence;
  85433. }
  85434. Object.defineProperty(MorphTarget.prototype, "influence", {
  85435. /**
  85436. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85437. */
  85438. get: function () {
  85439. return this._influence;
  85440. },
  85441. set: function (influence) {
  85442. if (this._influence === influence) {
  85443. return;
  85444. }
  85445. var previous = this._influence;
  85446. this._influence = influence;
  85447. if (this.onInfluenceChanged.hasObservers) {
  85448. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85449. }
  85450. },
  85451. enumerable: true,
  85452. configurable: true
  85453. });
  85454. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  85455. /**
  85456. * Gets or sets the animation properties override
  85457. */
  85458. get: function () {
  85459. if (!this._animationPropertiesOverride && this._scene) {
  85460. return this._scene.animationPropertiesOverride;
  85461. }
  85462. return this._animationPropertiesOverride;
  85463. },
  85464. set: function (value) {
  85465. this._animationPropertiesOverride = value;
  85466. },
  85467. enumerable: true,
  85468. configurable: true
  85469. });
  85470. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85471. /**
  85472. * Gets a boolean defining if the target contains position data
  85473. */
  85474. get: function () {
  85475. return !!this._positions;
  85476. },
  85477. enumerable: true,
  85478. configurable: true
  85479. });
  85480. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85481. /**
  85482. * Gets a boolean defining if the target contains normal data
  85483. */
  85484. get: function () {
  85485. return !!this._normals;
  85486. },
  85487. enumerable: true,
  85488. configurable: true
  85489. });
  85490. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85491. /**
  85492. * Gets a boolean defining if the target contains tangent data
  85493. */
  85494. get: function () {
  85495. return !!this._tangents;
  85496. },
  85497. enumerable: true,
  85498. configurable: true
  85499. });
  85500. /**
  85501. * Affects position data to this target
  85502. * @param data defines the position data to use
  85503. */
  85504. MorphTarget.prototype.setPositions = function (data) {
  85505. this._positions = data;
  85506. };
  85507. /**
  85508. * Gets the position data stored in this target
  85509. * @returns a FloatArray containing the position data (or null if not present)
  85510. */
  85511. MorphTarget.prototype.getPositions = function () {
  85512. return this._positions;
  85513. };
  85514. /**
  85515. * Affects normal data to this target
  85516. * @param data defines the normal data to use
  85517. */
  85518. MorphTarget.prototype.setNormals = function (data) {
  85519. this._normals = data;
  85520. };
  85521. /**
  85522. * Gets the normal data stored in this target
  85523. * @returns a FloatArray containing the normal data (or null if not present)
  85524. */
  85525. MorphTarget.prototype.getNormals = function () {
  85526. return this._normals;
  85527. };
  85528. /**
  85529. * Affects tangent data to this target
  85530. * @param data defines the tangent data to use
  85531. */
  85532. MorphTarget.prototype.setTangents = function (data) {
  85533. this._tangents = data;
  85534. };
  85535. /**
  85536. * Gets the tangent data stored in this target
  85537. * @returns a FloatArray containing the tangent data (or null if not present)
  85538. */
  85539. MorphTarget.prototype.getTangents = function () {
  85540. return this._tangents;
  85541. };
  85542. /**
  85543. * Serializes the current target into a Serialization object
  85544. * @returns the serialized object
  85545. */
  85546. MorphTarget.prototype.serialize = function () {
  85547. var serializationObject = {};
  85548. serializationObject.name = this.name;
  85549. serializationObject.influence = this.influence;
  85550. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85551. if (this.hasNormals) {
  85552. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85553. }
  85554. if (this.hasTangents) {
  85555. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85556. }
  85557. // Animations
  85558. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85559. return serializationObject;
  85560. };
  85561. // Statics
  85562. /**
  85563. * Creates a new target from serialized data
  85564. * @param serializationObject defines the serialized data to use
  85565. * @returns a new MorphTarget
  85566. */
  85567. MorphTarget.Parse = function (serializationObject) {
  85568. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85569. result.setPositions(serializationObject.positions);
  85570. if (serializationObject.normals) {
  85571. result.setNormals(serializationObject.normals);
  85572. }
  85573. if (serializationObject.tangents) {
  85574. result.setTangents(serializationObject.tangents);
  85575. }
  85576. // Animations
  85577. if (serializationObject.animations) {
  85578. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85579. var parsedAnimation = serializationObject.animations[animationIndex];
  85580. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85581. }
  85582. }
  85583. return result;
  85584. };
  85585. /**
  85586. * Creates a MorphTarget from mesh data
  85587. * @param mesh defines the source mesh
  85588. * @param name defines the name to use for the new target
  85589. * @param influence defines the influence to attach to the target
  85590. * @returns a new MorphTarget
  85591. */
  85592. MorphTarget.FromMesh = function (mesh, name, influence) {
  85593. if (!name) {
  85594. name = mesh.name;
  85595. }
  85596. var result = new MorphTarget(name, influence, mesh.getScene());
  85597. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85598. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85599. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85600. }
  85601. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85602. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85603. }
  85604. return result;
  85605. };
  85606. return MorphTarget;
  85607. }());
  85608. BABYLON.MorphTarget = MorphTarget;
  85609. })(BABYLON || (BABYLON = {}));
  85610. //# sourceMappingURL=babylon.morphTarget.js.map
  85611. var BABYLON;
  85612. (function (BABYLON) {
  85613. /**
  85614. * This class is used to deform meshes using morphing between different targets
  85615. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85616. */
  85617. var MorphTargetManager = /** @class */ (function () {
  85618. /**
  85619. * Creates a new MorphTargetManager
  85620. * @param scene defines the current scene
  85621. */
  85622. function MorphTargetManager(scene) {
  85623. if (scene === void 0) { scene = null; }
  85624. this._targets = new Array();
  85625. this._targetObservable = new Array();
  85626. this._activeTargets = new BABYLON.SmartArray(16);
  85627. this._supportsNormals = false;
  85628. this._supportsTangents = false;
  85629. this._vertexCount = 0;
  85630. this._uniqueId = 0;
  85631. this._tempInfluences = new Array();
  85632. if (!scene) {
  85633. scene = BABYLON.Engine.LastCreatedScene;
  85634. }
  85635. this._scene = scene;
  85636. if (this._scene) {
  85637. this._scene.morphTargetManagers.push(this);
  85638. this._uniqueId = this._scene.getUniqueId();
  85639. }
  85640. }
  85641. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85642. /**
  85643. * Gets the unique ID of this manager
  85644. */
  85645. get: function () {
  85646. return this._uniqueId;
  85647. },
  85648. enumerable: true,
  85649. configurable: true
  85650. });
  85651. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85652. /**
  85653. * Gets the number of vertices handled by this manager
  85654. */
  85655. get: function () {
  85656. return this._vertexCount;
  85657. },
  85658. enumerable: true,
  85659. configurable: true
  85660. });
  85661. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85662. /**
  85663. * Gets a boolean indicating if this manager supports morphing of normals
  85664. */
  85665. get: function () {
  85666. return this._supportsNormals;
  85667. },
  85668. enumerable: true,
  85669. configurable: true
  85670. });
  85671. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85672. /**
  85673. * Gets a boolean indicating if this manager supports morphing of tangents
  85674. */
  85675. get: function () {
  85676. return this._supportsTangents;
  85677. },
  85678. enumerable: true,
  85679. configurable: true
  85680. });
  85681. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85682. /**
  85683. * Gets the number of targets stored in this manager
  85684. */
  85685. get: function () {
  85686. return this._targets.length;
  85687. },
  85688. enumerable: true,
  85689. configurable: true
  85690. });
  85691. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85692. /**
  85693. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85694. */
  85695. get: function () {
  85696. return this._activeTargets.length;
  85697. },
  85698. enumerable: true,
  85699. configurable: true
  85700. });
  85701. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85702. /**
  85703. * Gets the list of influences (one per target)
  85704. */
  85705. get: function () {
  85706. return this._influences;
  85707. },
  85708. enumerable: true,
  85709. configurable: true
  85710. });
  85711. /**
  85712. * Gets the active target at specified index. An active target is a target with an influence > 0
  85713. * @param index defines the index to check
  85714. * @returns the requested target
  85715. */
  85716. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85717. return this._activeTargets.data[index];
  85718. };
  85719. /**
  85720. * Gets the target at specified index
  85721. * @param index defines the index to check
  85722. * @returns the requested target
  85723. */
  85724. MorphTargetManager.prototype.getTarget = function (index) {
  85725. return this._targets[index];
  85726. };
  85727. /**
  85728. * Add a new target to this manager
  85729. * @param target defines the target to add
  85730. */
  85731. MorphTargetManager.prototype.addTarget = function (target) {
  85732. var _this = this;
  85733. this._targets.push(target);
  85734. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85735. _this._syncActiveTargets(needUpdate);
  85736. }));
  85737. this._syncActiveTargets(true);
  85738. };
  85739. /**
  85740. * Removes a target from the manager
  85741. * @param target defines the target to remove
  85742. */
  85743. MorphTargetManager.prototype.removeTarget = function (target) {
  85744. var index = this._targets.indexOf(target);
  85745. if (index >= 0) {
  85746. this._targets.splice(index, 1);
  85747. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85748. this._syncActiveTargets(true);
  85749. }
  85750. };
  85751. /**
  85752. * Serializes the current manager into a Serialization object
  85753. * @returns the serialized object
  85754. */
  85755. MorphTargetManager.prototype.serialize = function () {
  85756. var serializationObject = {};
  85757. serializationObject.id = this.uniqueId;
  85758. serializationObject.targets = [];
  85759. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85760. var target = _a[_i];
  85761. serializationObject.targets.push(target.serialize());
  85762. }
  85763. return serializationObject;
  85764. };
  85765. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85766. var influenceCount = 0;
  85767. this._activeTargets.reset();
  85768. this._supportsNormals = true;
  85769. this._supportsTangents = true;
  85770. this._vertexCount = 0;
  85771. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85772. var target = _a[_i];
  85773. this._activeTargets.push(target);
  85774. this._tempInfluences[influenceCount++] = target.influence;
  85775. var positions = target.getPositions();
  85776. if (positions) {
  85777. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85778. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85779. var vertexCount = positions.length / 3;
  85780. if (this._vertexCount === 0) {
  85781. this._vertexCount = vertexCount;
  85782. }
  85783. else if (this._vertexCount !== vertexCount) {
  85784. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85785. return;
  85786. }
  85787. }
  85788. }
  85789. if (!this._influences || this._influences.length !== influenceCount) {
  85790. this._influences = new Float32Array(influenceCount);
  85791. }
  85792. for (var index = 0; index < influenceCount; index++) {
  85793. this._influences[index] = this._tempInfluences[index];
  85794. }
  85795. if (needUpdate) {
  85796. this.synchronize();
  85797. }
  85798. };
  85799. /**
  85800. * Syncrhonize the targets with all the meshes using this morph target manager
  85801. */
  85802. MorphTargetManager.prototype.synchronize = function () {
  85803. if (!this._scene) {
  85804. return;
  85805. }
  85806. // Flag meshes as dirty to resync with the active targets
  85807. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85808. var mesh = _a[_i];
  85809. if (mesh.morphTargetManager === this) {
  85810. mesh._syncGeometryWithMorphTargetManager();
  85811. }
  85812. }
  85813. };
  85814. // Statics
  85815. /**
  85816. * Creates a new MorphTargetManager from serialized data
  85817. * @param serializationObject defines the serialized data
  85818. * @param scene defines the hosting scene
  85819. * @returns the new MorphTargetManager
  85820. */
  85821. MorphTargetManager.Parse = function (serializationObject, scene) {
  85822. var result = new MorphTargetManager(scene);
  85823. result._uniqueId = serializationObject.id;
  85824. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85825. var targetData = _a[_i];
  85826. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85827. }
  85828. return result;
  85829. };
  85830. return MorphTargetManager;
  85831. }());
  85832. BABYLON.MorphTargetManager = MorphTargetManager;
  85833. })(BABYLON || (BABYLON = {}));
  85834. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85835. var BABYLON;
  85836. (function (BABYLON) {
  85837. var Octree = /** @class */ (function () {
  85838. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85839. if (maxDepth === void 0) { maxDepth = 2; }
  85840. this.maxDepth = maxDepth;
  85841. this.dynamicContent = new Array();
  85842. this._maxBlockCapacity = maxBlockCapacity || 64;
  85843. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85844. this._creationFunc = creationFunc;
  85845. }
  85846. // Methods
  85847. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85848. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85849. };
  85850. Octree.prototype.addMesh = function (entry) {
  85851. for (var index = 0; index < this.blocks.length; index++) {
  85852. var block = this.blocks[index];
  85853. block.addEntry(entry);
  85854. }
  85855. };
  85856. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85857. this._selectionContent.reset();
  85858. for (var index = 0; index < this.blocks.length; index++) {
  85859. var block = this.blocks[index];
  85860. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85861. }
  85862. if (allowDuplicate) {
  85863. this._selectionContent.concat(this.dynamicContent);
  85864. }
  85865. else {
  85866. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85867. }
  85868. return this._selectionContent;
  85869. };
  85870. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85871. this._selectionContent.reset();
  85872. for (var index = 0; index < this.blocks.length; index++) {
  85873. var block = this.blocks[index];
  85874. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85875. }
  85876. if (allowDuplicate) {
  85877. this._selectionContent.concat(this.dynamicContent);
  85878. }
  85879. else {
  85880. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85881. }
  85882. return this._selectionContent;
  85883. };
  85884. Octree.prototype.intersectsRay = function (ray) {
  85885. this._selectionContent.reset();
  85886. for (var index = 0; index < this.blocks.length; index++) {
  85887. var block = this.blocks[index];
  85888. block.intersectsRay(ray, this._selectionContent);
  85889. }
  85890. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85891. return this._selectionContent;
  85892. };
  85893. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85894. target.blocks = new Array();
  85895. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  85896. // Segmenting space
  85897. for (var x = 0; x < 2; x++) {
  85898. for (var y = 0; y < 2; y++) {
  85899. for (var z = 0; z < 2; z++) {
  85900. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  85901. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  85902. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  85903. block.addEntries(entries);
  85904. target.blocks.push(block);
  85905. }
  85906. }
  85907. }
  85908. };
  85909. Octree.CreationFuncForMeshes = function (entry, block) {
  85910. var boundingInfo = entry.getBoundingInfo();
  85911. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85912. block.entries.push(entry);
  85913. }
  85914. };
  85915. Octree.CreationFuncForSubMeshes = function (entry, block) {
  85916. var boundingInfo = entry.getBoundingInfo();
  85917. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85918. block.entries.push(entry);
  85919. }
  85920. };
  85921. return Octree;
  85922. }());
  85923. BABYLON.Octree = Octree;
  85924. })(BABYLON || (BABYLON = {}));
  85925. //# sourceMappingURL=babylon.octree.js.map
  85926. var BABYLON;
  85927. (function (BABYLON) {
  85928. var OctreeBlock = /** @class */ (function () {
  85929. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  85930. this.entries = new Array();
  85931. this._boundingVectors = new Array();
  85932. this._capacity = capacity;
  85933. this._depth = depth;
  85934. this._maxDepth = maxDepth;
  85935. this._creationFunc = creationFunc;
  85936. this._minPoint = minPoint;
  85937. this._maxPoint = maxPoint;
  85938. this._boundingVectors.push(minPoint.clone());
  85939. this._boundingVectors.push(maxPoint.clone());
  85940. this._boundingVectors.push(minPoint.clone());
  85941. this._boundingVectors[2].x = maxPoint.x;
  85942. this._boundingVectors.push(minPoint.clone());
  85943. this._boundingVectors[3].y = maxPoint.y;
  85944. this._boundingVectors.push(minPoint.clone());
  85945. this._boundingVectors[4].z = maxPoint.z;
  85946. this._boundingVectors.push(maxPoint.clone());
  85947. this._boundingVectors[5].z = minPoint.z;
  85948. this._boundingVectors.push(maxPoint.clone());
  85949. this._boundingVectors[6].x = minPoint.x;
  85950. this._boundingVectors.push(maxPoint.clone());
  85951. this._boundingVectors[7].y = minPoint.y;
  85952. }
  85953. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  85954. // Property
  85955. get: function () {
  85956. return this._capacity;
  85957. },
  85958. enumerable: true,
  85959. configurable: true
  85960. });
  85961. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  85962. get: function () {
  85963. return this._minPoint;
  85964. },
  85965. enumerable: true,
  85966. configurable: true
  85967. });
  85968. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  85969. get: function () {
  85970. return this._maxPoint;
  85971. },
  85972. enumerable: true,
  85973. configurable: true
  85974. });
  85975. // Methods
  85976. OctreeBlock.prototype.addEntry = function (entry) {
  85977. if (this.blocks) {
  85978. for (var index = 0; index < this.blocks.length; index++) {
  85979. var block = this.blocks[index];
  85980. block.addEntry(entry);
  85981. }
  85982. return;
  85983. }
  85984. this._creationFunc(entry, this);
  85985. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  85986. this.createInnerBlocks();
  85987. }
  85988. };
  85989. OctreeBlock.prototype.addEntries = function (entries) {
  85990. for (var index = 0; index < entries.length; index++) {
  85991. var mesh = entries[index];
  85992. this.addEntry(mesh);
  85993. }
  85994. };
  85995. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  85996. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  85997. if (this.blocks) {
  85998. for (var index = 0; index < this.blocks.length; index++) {
  85999. var block = this.blocks[index];
  86000. block.select(frustumPlanes, selection, allowDuplicate);
  86001. }
  86002. return;
  86003. }
  86004. if (allowDuplicate) {
  86005. selection.concat(this.entries);
  86006. }
  86007. else {
  86008. selection.concatWithNoDuplicate(this.entries);
  86009. }
  86010. }
  86011. };
  86012. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86013. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86014. if (this.blocks) {
  86015. for (var index = 0; index < this.blocks.length; index++) {
  86016. var block = this.blocks[index];
  86017. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86018. }
  86019. return;
  86020. }
  86021. if (allowDuplicate) {
  86022. selection.concat(this.entries);
  86023. }
  86024. else {
  86025. selection.concatWithNoDuplicate(this.entries);
  86026. }
  86027. }
  86028. };
  86029. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86030. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86031. if (this.blocks) {
  86032. for (var index = 0; index < this.blocks.length; index++) {
  86033. var block = this.blocks[index];
  86034. block.intersectsRay(ray, selection);
  86035. }
  86036. return;
  86037. }
  86038. selection.concatWithNoDuplicate(this.entries);
  86039. }
  86040. };
  86041. OctreeBlock.prototype.createInnerBlocks = function () {
  86042. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86043. };
  86044. return OctreeBlock;
  86045. }());
  86046. BABYLON.OctreeBlock = OctreeBlock;
  86047. })(BABYLON || (BABYLON = {}));
  86048. //# sourceMappingURL=babylon.octreeBlock.js.map
  86049. var BABYLON;
  86050. (function (BABYLON) {
  86051. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86052. __extends(VRDistortionCorrectionPostProcess, _super);
  86053. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86054. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86055. 'LensCenter',
  86056. 'Scale',
  86057. 'ScaleIn',
  86058. 'HmdWarpParam'
  86059. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86060. _this._isRightEye = isRightEye;
  86061. _this._distortionFactors = vrMetrics.distortionK;
  86062. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86063. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86064. _this.adaptScaleToCurrentViewport = true;
  86065. _this.onSizeChangedObservable.add(function () {
  86066. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86067. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86068. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86069. });
  86070. _this.onApplyObservable.add(function (effect) {
  86071. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86072. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86073. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86074. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86075. });
  86076. return _this;
  86077. }
  86078. return VRDistortionCorrectionPostProcess;
  86079. }(BABYLON.PostProcess));
  86080. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86081. })(BABYLON || (BABYLON = {}));
  86082. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86083. var BABYLON;
  86084. (function (BABYLON) {
  86085. /**
  86086. * Postprocess used to generate anaglyphic rendering
  86087. */
  86088. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86089. __extends(AnaglyphPostProcess, _super);
  86090. /**
  86091. * Creates a new AnaglyphPostProcess
  86092. * @param name defines postprocess name
  86093. * @param options defines creation options or target ratio scale
  86094. * @param rigCameras defines cameras using this postprocess
  86095. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86096. * @param engine defines hosting engine
  86097. * @param reusable defines if the postprocess will be reused multiple times per frame
  86098. */
  86099. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86100. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86101. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86102. _this.onApplyObservable.add(function (effect) {
  86103. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86104. });
  86105. return _this;
  86106. }
  86107. return AnaglyphPostProcess;
  86108. }(BABYLON.PostProcess));
  86109. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86110. })(BABYLON || (BABYLON = {}));
  86111. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86112. var BABYLON;
  86113. (function (BABYLON) {
  86114. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86115. __extends(StereoscopicInterlacePostProcess, _super);
  86116. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86117. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86118. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86119. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86120. _this.onSizeChangedObservable.add(function () {
  86121. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86122. });
  86123. _this.onApplyObservable.add(function (effect) {
  86124. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86125. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86126. });
  86127. return _this;
  86128. }
  86129. return StereoscopicInterlacePostProcess;
  86130. }(BABYLON.PostProcess));
  86131. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86132. })(BABYLON || (BABYLON = {}));
  86133. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86134. var BABYLON;
  86135. (function (BABYLON) {
  86136. /**
  86137. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86138. * Screen rotation is taken into account.
  86139. */
  86140. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86141. function FreeCameraDeviceOrientationInput() {
  86142. var _this = this;
  86143. this._screenOrientationAngle = 0;
  86144. this._screenQuaternion = new BABYLON.Quaternion();
  86145. this._alpha = 0;
  86146. this._beta = 0;
  86147. this._gamma = 0;
  86148. this._orientationChanged = function () {
  86149. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86150. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86151. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86152. };
  86153. this._deviceOrientation = function (evt) {
  86154. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86155. _this._beta = evt.beta !== null ? evt.beta : 0;
  86156. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86157. };
  86158. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86159. this._orientationChanged();
  86160. }
  86161. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86162. get: function () {
  86163. return this._camera;
  86164. },
  86165. set: function (camera) {
  86166. this._camera = camera;
  86167. if (this._camera != null && !this._camera.rotationQuaternion) {
  86168. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86169. }
  86170. },
  86171. enumerable: true,
  86172. configurable: true
  86173. });
  86174. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86175. window.addEventListener("orientationchange", this._orientationChanged);
  86176. window.addEventListener("deviceorientation", this._deviceOrientation);
  86177. //In certain cases, the attach control is called AFTER orientation was changed,
  86178. //So this is needed.
  86179. this._orientationChanged();
  86180. };
  86181. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86182. window.removeEventListener("orientationchange", this._orientationChanged);
  86183. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86184. };
  86185. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86186. //if no device orientation provided, don't update the rotation.
  86187. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86188. if (!this._alpha)
  86189. return;
  86190. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86191. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86192. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86193. //Mirror on XY Plane
  86194. this._camera.rotationQuaternion.z *= -1;
  86195. this._camera.rotationQuaternion.w *= -1;
  86196. };
  86197. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86198. return "FreeCameraDeviceOrientationInput";
  86199. };
  86200. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86201. return "deviceOrientation";
  86202. };
  86203. return FreeCameraDeviceOrientationInput;
  86204. }());
  86205. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86206. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86207. })(BABYLON || (BABYLON = {}));
  86208. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86209. var BABYLON;
  86210. (function (BABYLON) {
  86211. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86212. function ArcRotateCameraVRDeviceOrientationInput() {
  86213. this.alphaCorrection = 1;
  86214. this.betaCorrection = 1;
  86215. this.gammaCorrection = 1;
  86216. this._alpha = 0;
  86217. this._gamma = 0;
  86218. this._dirty = false;
  86219. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86220. }
  86221. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86222. this.camera.attachControl(element, noPreventDefault);
  86223. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86224. };
  86225. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86226. if (evt.alpha !== null) {
  86227. this._alpha = +evt.alpha | 0;
  86228. }
  86229. if (evt.gamma !== null) {
  86230. this._gamma = +evt.gamma | 0;
  86231. }
  86232. this._dirty = true;
  86233. };
  86234. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86235. if (this._dirty) {
  86236. this._dirty = false;
  86237. if (this._gamma < 0) {
  86238. this._gamma = 180 + this._gamma;
  86239. }
  86240. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86241. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86242. }
  86243. };
  86244. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86245. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86246. };
  86247. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86248. return "ArcRotateCameraVRDeviceOrientationInput";
  86249. };
  86250. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86251. return "VRDeviceOrientation";
  86252. };
  86253. return ArcRotateCameraVRDeviceOrientationInput;
  86254. }());
  86255. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86256. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86257. })(BABYLON || (BABYLON = {}));
  86258. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86259. var BABYLON;
  86260. (function (BABYLON) {
  86261. var VRCameraMetrics = /** @class */ (function () {
  86262. function VRCameraMetrics() {
  86263. this.compensateDistortion = true;
  86264. }
  86265. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86266. get: function () {
  86267. return this.hResolution / (2 * this.vResolution);
  86268. },
  86269. enumerable: true,
  86270. configurable: true
  86271. });
  86272. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86273. get: function () {
  86274. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86275. },
  86276. enumerable: true,
  86277. configurable: true
  86278. });
  86279. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86280. get: function () {
  86281. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86282. var h = (4 * meters) / this.hScreenSize;
  86283. return BABYLON.Matrix.Translation(h, 0, 0);
  86284. },
  86285. enumerable: true,
  86286. configurable: true
  86287. });
  86288. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86289. get: function () {
  86290. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86291. var h = (4 * meters) / this.hScreenSize;
  86292. return BABYLON.Matrix.Translation(-h, 0, 0);
  86293. },
  86294. enumerable: true,
  86295. configurable: true
  86296. });
  86297. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86298. get: function () {
  86299. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86300. },
  86301. enumerable: true,
  86302. configurable: true
  86303. });
  86304. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86305. get: function () {
  86306. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86307. },
  86308. enumerable: true,
  86309. configurable: true
  86310. });
  86311. VRCameraMetrics.GetDefault = function () {
  86312. var result = new VRCameraMetrics();
  86313. result.hResolution = 1280;
  86314. result.vResolution = 800;
  86315. result.hScreenSize = 0.149759993;
  86316. result.vScreenSize = 0.0935999975;
  86317. result.vScreenCenter = 0.0467999987;
  86318. result.eyeToScreenDistance = 0.0410000011;
  86319. result.lensSeparationDistance = 0.0635000020;
  86320. result.interpupillaryDistance = 0.0640000030;
  86321. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86322. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86323. result.postProcessScaleFactor = 1.714605507808412;
  86324. result.lensCenterOffset = 0.151976421;
  86325. return result;
  86326. };
  86327. return VRCameraMetrics;
  86328. }());
  86329. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86330. })(BABYLON || (BABYLON = {}));
  86331. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86332. var BABYLON;
  86333. (function (BABYLON) {
  86334. /**
  86335. * This represents a WebVR camera.
  86336. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86337. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86338. */
  86339. var WebVRFreeCamera = /** @class */ (function (_super) {
  86340. __extends(WebVRFreeCamera, _super);
  86341. /**
  86342. * Instantiates a WebVRFreeCamera.
  86343. * @param name The name of the WebVRFreeCamera
  86344. * @param position The starting anchor position for the camera
  86345. * @param scene The scene the camera belongs to
  86346. * @param webVROptions a set of customizable options for the webVRCamera
  86347. */
  86348. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86349. if (webVROptions === void 0) { webVROptions = {}; }
  86350. var _this = _super.call(this, name, position, scene) || this;
  86351. _this.webVROptions = webVROptions;
  86352. /**
  86353. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86354. */
  86355. _this._vrDevice = null;
  86356. /**
  86357. * The rawPose of the vrDevice.
  86358. */
  86359. _this.rawPose = null;
  86360. _this._specsVersion = "1.1";
  86361. _this._attached = false;
  86362. _this._descendants = [];
  86363. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86364. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86365. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86366. _this._standingMatrix = null;
  86367. /**
  86368. * Represents device position in babylon space.
  86369. */
  86370. _this.devicePosition = BABYLON.Vector3.Zero();
  86371. /**
  86372. * Represents device rotation in babylon space.
  86373. */
  86374. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86375. /**
  86376. * The scale of the device to be used when translating from device space to babylon space.
  86377. */
  86378. _this.deviceScaleFactor = 1;
  86379. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86380. _this._worldToDevice = BABYLON.Matrix.Identity();
  86381. /**
  86382. * References to the webVR controllers for the vrDevice.
  86383. */
  86384. _this.controllers = [];
  86385. /**
  86386. * Emits an event when a controller is attached.
  86387. */
  86388. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86389. /**
  86390. * Emits an event when a controller's mesh has been loaded;
  86391. */
  86392. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86393. /**
  86394. * If the rig cameras be used as parent instead of this camera.
  86395. */
  86396. _this.rigParenting = true;
  86397. _this._defaultHeight = undefined;
  86398. _this._workingVector = BABYLON.Vector3.Zero();
  86399. _this._oneVector = BABYLON.Vector3.One();
  86400. _this._workingMatrix = BABYLON.Matrix.Identity();
  86401. _this._cache.position = BABYLON.Vector3.Zero();
  86402. if (webVROptions.defaultHeight) {
  86403. _this._defaultHeight = webVROptions.defaultHeight;
  86404. _this.position.y = _this._defaultHeight;
  86405. }
  86406. _this.minZ = 0.1;
  86407. //legacy support - the compensation boolean was removed.
  86408. if (arguments.length === 5) {
  86409. _this.webVROptions = arguments[4];
  86410. }
  86411. // default webVR options
  86412. if (_this.webVROptions.trackPosition == undefined) {
  86413. _this.webVROptions.trackPosition = true;
  86414. }
  86415. if (_this.webVROptions.controllerMeshes == undefined) {
  86416. _this.webVROptions.controllerMeshes = true;
  86417. }
  86418. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86419. _this.webVROptions.defaultLightingOnControllers = true;
  86420. }
  86421. _this.rotationQuaternion = new BABYLON.Quaternion();
  86422. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86423. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86424. }
  86425. //enable VR
  86426. var engine = _this.getEngine();
  86427. _this._onVREnabled = function (success) { if (success) {
  86428. _this.initControllers();
  86429. } };
  86430. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86431. engine.initWebVR().add(function (event) {
  86432. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86433. return;
  86434. }
  86435. _this._vrDevice = event.vrDisplay;
  86436. //reset the rig parameters.
  86437. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86438. if (_this._attached) {
  86439. _this.getEngine().enableVR();
  86440. }
  86441. });
  86442. if (typeof (VRFrameData) !== "undefined")
  86443. _this._frameData = new VRFrameData();
  86444. /**
  86445. * The idea behind the following lines:
  86446. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86447. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86448. * the second will not show it correctly.
  86449. *
  86450. * To solve this - each object that has the camera as parent will be added to a protected array.
  86451. * When the rig camera renders, it will take this array and set all of those to be its children.
  86452. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86453. * Amazing!
  86454. */
  86455. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86456. if (camera.parent === _this && _this.rigParenting) {
  86457. _this._descendants = _this.getDescendants(true, function (n) {
  86458. // don't take the cameras or the controllers!
  86459. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86460. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86461. return !isController && !isRigCamera;
  86462. });
  86463. _this._descendants.forEach(function (node) {
  86464. node.parent = camera;
  86465. });
  86466. }
  86467. });
  86468. scene.onAfterCameraRenderObservable.add(function (camera) {
  86469. if (camera.parent === _this && _this.rigParenting) {
  86470. _this._descendants.forEach(function (node) {
  86471. node.parent = _this;
  86472. });
  86473. }
  86474. });
  86475. return _this;
  86476. }
  86477. /**
  86478. * Gets the device distance from the ground in meters.
  86479. * @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.
  86480. */
  86481. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86482. if (this._standingMatrix) {
  86483. // Add standing matrix offset to get real offset from ground in room
  86484. this._standingMatrix.getTranslationToRef(this._workingVector);
  86485. return this._deviceRoomPosition.y + this._workingVector.y;
  86486. }
  86487. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86488. return this._defaultHeight || 0;
  86489. };
  86490. /**
  86491. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86492. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86493. */
  86494. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86495. var _this = this;
  86496. if (callback === void 0) { callback = function (bool) { }; }
  86497. // Use standing matrix if available
  86498. this.getEngine().initWebVRAsync().then(function (result) {
  86499. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86500. callback(false);
  86501. }
  86502. else {
  86503. _this._standingMatrix = new BABYLON.Matrix();
  86504. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86505. if (!_this.getScene().useRightHandedSystem) {
  86506. [2, 6, 8, 9, 14].forEach(function (num) {
  86507. if (_this._standingMatrix) {
  86508. _this._standingMatrix.m[num] *= -1;
  86509. }
  86510. });
  86511. }
  86512. callback(true);
  86513. }
  86514. });
  86515. };
  86516. /**
  86517. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86518. * @returns A promise with a boolean set to if the standing matrix is supported.
  86519. */
  86520. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86521. var _this = this;
  86522. return new Promise(function (res, rej) {
  86523. _this.useStandingMatrix(function (supported) {
  86524. res(supported);
  86525. });
  86526. });
  86527. };
  86528. /**
  86529. * Disposes the camera
  86530. */
  86531. WebVRFreeCamera.prototype.dispose = function () {
  86532. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86533. _super.prototype.dispose.call(this);
  86534. };
  86535. /**
  86536. * Gets a vrController by name.
  86537. * @param name The name of the controller to retreive
  86538. * @returns the controller matching the name specified or null if not found
  86539. */
  86540. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86541. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86542. var gp = _a[_i];
  86543. if (gp.hand === name) {
  86544. return gp;
  86545. }
  86546. }
  86547. return null;
  86548. };
  86549. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86550. /**
  86551. * The controller corrisponding to the users left hand.
  86552. */
  86553. get: function () {
  86554. if (!this._leftController) {
  86555. this._leftController = this.getControllerByName("left");
  86556. }
  86557. return this._leftController;
  86558. },
  86559. enumerable: true,
  86560. configurable: true
  86561. });
  86562. ;
  86563. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86564. /**
  86565. * The controller corrisponding to the users right hand.
  86566. */
  86567. get: function () {
  86568. if (!this._rightController) {
  86569. this._rightController = this.getControllerByName("right");
  86570. }
  86571. return this._rightController;
  86572. },
  86573. enumerable: true,
  86574. configurable: true
  86575. });
  86576. ;
  86577. /**
  86578. * Casts a ray forward from the vrCamera's gaze.
  86579. * @param length Length of the ray (default: 100)
  86580. * @returns the ray corrisponding to the gaze
  86581. */
  86582. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86583. if (length === void 0) { length = 100; }
  86584. if (this.leftCamera) {
  86585. // Use left eye to avoid computation to compute center on every call
  86586. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86587. }
  86588. else {
  86589. return _super.prototype.getForwardRay.call(this, length);
  86590. }
  86591. };
  86592. /**
  86593. * Updates the camera based on device's frame data
  86594. */
  86595. WebVRFreeCamera.prototype._checkInputs = function () {
  86596. if (this._vrDevice && this._vrDevice.isPresenting) {
  86597. this._vrDevice.getFrameData(this._frameData);
  86598. this.updateFromDevice(this._frameData.pose);
  86599. }
  86600. _super.prototype._checkInputs.call(this);
  86601. };
  86602. /**
  86603. * Updates the poseControlled values based on the input device pose.
  86604. * @param poseData Pose coming from the device
  86605. */
  86606. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86607. if (poseData && poseData.orientation) {
  86608. this.rawPose = poseData;
  86609. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86610. if (this.getScene().useRightHandedSystem) {
  86611. this._deviceRoomRotationQuaternion.z *= -1;
  86612. this._deviceRoomRotationQuaternion.w *= -1;
  86613. }
  86614. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86615. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86616. if (this.getScene().useRightHandedSystem) {
  86617. this._deviceRoomPosition.z *= -1;
  86618. }
  86619. }
  86620. }
  86621. };
  86622. /**
  86623. * WebVR's attach control will start broadcasting frames to the device.
  86624. * Note that in certain browsers (chrome for example) this function must be called
  86625. * within a user-interaction callback. Example:
  86626. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86627. *
  86628. * @param element html element to attach the vrDevice to
  86629. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86630. */
  86631. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86632. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86633. this._attached = true;
  86634. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86635. if (this._vrDevice) {
  86636. this.getEngine().enableVR();
  86637. }
  86638. };
  86639. /**
  86640. * Detaches the camera from the html element and disables VR
  86641. *
  86642. * @param element html element to detach from
  86643. */
  86644. WebVRFreeCamera.prototype.detachControl = function (element) {
  86645. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86646. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86647. _super.prototype.detachControl.call(this, element);
  86648. this._attached = false;
  86649. this.getEngine().disableVR();
  86650. };
  86651. /**
  86652. * @returns the name of this class
  86653. */
  86654. WebVRFreeCamera.prototype.getClassName = function () {
  86655. return "WebVRFreeCamera";
  86656. };
  86657. /**
  86658. * Calls resetPose on the vrDisplay
  86659. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86660. */
  86661. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86662. //uses the vrDisplay's "resetPose()".
  86663. //pitch and roll won't be affected.
  86664. this._vrDevice.resetPose();
  86665. };
  86666. /**
  86667. * Updates the rig cameras (left and right eye)
  86668. */
  86669. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86670. var camLeft = this._rigCameras[0];
  86671. var camRight = this._rigCameras[1];
  86672. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86673. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86674. camLeft.position.copyFrom(this._deviceRoomPosition);
  86675. camRight.position.copyFrom(this._deviceRoomPosition);
  86676. };
  86677. /**
  86678. * Updates the cached values of the camera
  86679. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86680. */
  86681. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86682. var _this = this;
  86683. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86684. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86685. if (!this.updateCacheCalled) {
  86686. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86687. this.updateCacheCalled = true;
  86688. this.update();
  86689. }
  86690. // Set working vector to the device position in room space rotated by the new rotation
  86691. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86692. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86693. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86694. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86695. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86696. // Add translation from anchor position
  86697. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86698. this._workingVector.addInPlace(this.position);
  86699. this._workingVector.subtractInPlace(this._cache.position);
  86700. this._deviceToWorld.setTranslation(this._workingVector);
  86701. // Set an inverted matrix to be used when updating the camera
  86702. this._deviceToWorld.invertToRef(this._worldToDevice);
  86703. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86704. this.controllers.forEach(function (controller) {
  86705. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86706. controller.update();
  86707. });
  86708. }
  86709. if (!ignoreParentClass) {
  86710. _super.prototype._updateCache.call(this);
  86711. }
  86712. this.updateCacheCalled = false;
  86713. };
  86714. /**
  86715. * Updates the current device position and rotation in the babylon world
  86716. */
  86717. WebVRFreeCamera.prototype.update = function () {
  86718. // Get current device position in babylon world
  86719. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86720. // Get current device rotation in babylon world
  86721. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86722. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86723. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86724. _super.prototype.update.call(this);
  86725. };
  86726. /**
  86727. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86728. * @returns an identity matrix
  86729. */
  86730. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86731. return BABYLON.Matrix.Identity();
  86732. };
  86733. /**
  86734. * This function is called by the two RIG cameras.
  86735. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86736. */
  86737. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86738. var _this = this;
  86739. // Update the parent camera prior to using a child camera to avoid desynchronization
  86740. var parentCamera = this._cameraRigParams["parentCamera"];
  86741. parentCamera._updateCache();
  86742. //WebVR 1.1
  86743. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86744. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86745. if (!this.getScene().useRightHandedSystem) {
  86746. [2, 6, 8, 9, 14].forEach(function (num) {
  86747. _this._webvrViewMatrix.m[num] *= -1;
  86748. });
  86749. }
  86750. // update the camera rotation matrix
  86751. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86752. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86753. // Computing target and final matrix
  86754. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86755. // should the view matrix be updated with scale and position offset?
  86756. if (parentCamera.deviceScaleFactor !== 1) {
  86757. this._webvrViewMatrix.invert();
  86758. // scale the position, if set
  86759. if (parentCamera.deviceScaleFactor) {
  86760. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86761. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86762. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86763. }
  86764. this._webvrViewMatrix.invert();
  86765. }
  86766. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86767. // Compute global position
  86768. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  86769. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  86770. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  86771. this._workingMatrix.getTranslationToRef(this._globalPosition);
  86772. this._markSyncedWithParent();
  86773. return this._webvrViewMatrix;
  86774. };
  86775. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86776. var _this = this;
  86777. var parentCamera = this.parent;
  86778. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86779. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86780. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86781. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86782. //babylon compatible matrix
  86783. if (!this.getScene().useRightHandedSystem) {
  86784. [8, 9, 10, 11].forEach(function (num) {
  86785. _this._projectionMatrix.m[num] *= -1;
  86786. });
  86787. }
  86788. return this._projectionMatrix;
  86789. };
  86790. /**
  86791. * Initializes the controllers and their meshes
  86792. */
  86793. WebVRFreeCamera.prototype.initControllers = function () {
  86794. var _this = this;
  86795. this.controllers = [];
  86796. var manager = this.getScene().gamepadManager;
  86797. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86798. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86799. var webVrController = gamepad;
  86800. if (webVrController.defaultModel) {
  86801. webVrController.defaultModel.setEnabled(false);
  86802. }
  86803. if (webVrController.hand === "right") {
  86804. _this._rightController = null;
  86805. }
  86806. if (webVrController.hand === "left") {
  86807. _this._leftController = null;
  86808. }
  86809. var controllerIndex = _this.controllers.indexOf(webVrController);
  86810. if (controllerIndex !== -1) {
  86811. _this.controllers.splice(controllerIndex, 1);
  86812. }
  86813. }
  86814. });
  86815. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86816. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86817. var webVrController_1 = gamepad;
  86818. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86819. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86820. if (_this.webVROptions.controllerMeshes) {
  86821. if (webVrController_1.defaultModel) {
  86822. webVrController_1.defaultModel.setEnabled(true);
  86823. }
  86824. else {
  86825. // Load the meshes
  86826. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86827. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86828. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86829. if (_this.webVROptions.defaultLightingOnControllers) {
  86830. if (!_this._lightOnControllers) {
  86831. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86832. }
  86833. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86834. var children = mesh.getChildren();
  86835. if (children.length !== 0) {
  86836. children.forEach(function (mesh) {
  86837. light.includedOnlyMeshes.push(mesh);
  86838. activateLightOnSubMeshes_1(mesh, light);
  86839. });
  86840. }
  86841. };
  86842. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86843. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86844. }
  86845. });
  86846. }
  86847. }
  86848. webVrController_1.attachToPoseControlledCamera(_this);
  86849. // since this is async - sanity check. Is the controller already stored?
  86850. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86851. //add to the controllers array
  86852. _this.controllers.push(webVrController_1);
  86853. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86854. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86855. // So we're overriding setting left & right manually to be sure
  86856. var firstViveWandDetected = false;
  86857. for (var i = 0; i < _this.controllers.length; i++) {
  86858. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86859. if (!firstViveWandDetected) {
  86860. firstViveWandDetected = true;
  86861. _this.controllers[i].hand = "left";
  86862. }
  86863. else {
  86864. _this.controllers[i].hand = "right";
  86865. }
  86866. }
  86867. }
  86868. //did we find enough controllers? Great! let the developer know.
  86869. if (_this.controllers.length >= 2) {
  86870. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86871. }
  86872. }
  86873. }
  86874. });
  86875. };
  86876. return WebVRFreeCamera;
  86877. }(BABYLON.FreeCamera));
  86878. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86879. })(BABYLON || (BABYLON = {}));
  86880. //# sourceMappingURL=babylon.webVRCamera.js.map
  86881. var BABYLON;
  86882. (function (BABYLON) {
  86883. // We're mainly based on the logic defined into the FreeCamera code
  86884. /**
  86885. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86886. * being tilted forward or back and left or right.
  86887. */
  86888. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86889. __extends(DeviceOrientationCamera, _super);
  86890. /**
  86891. * Creates a new device orientation camera
  86892. * @param name The name of the camera
  86893. * @param position The start position camera
  86894. * @param scene The scene the camera belongs to
  86895. */
  86896. function DeviceOrientationCamera(name, position, scene) {
  86897. var _this = _super.call(this, name, position, scene) || this;
  86898. _this._quaternionCache = new BABYLON.Quaternion();
  86899. _this.inputs.addDeviceOrientation();
  86900. return _this;
  86901. }
  86902. /**
  86903. * Gets the current instance class name ("DeviceOrientationCamera").
  86904. * This helps avoiding instanceof at run time.
  86905. * @returns the class name
  86906. */
  86907. DeviceOrientationCamera.prototype.getClassName = function () {
  86908. return "DeviceOrientationCamera";
  86909. };
  86910. /**
  86911. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  86912. */
  86913. DeviceOrientationCamera.prototype._checkInputs = function () {
  86914. _super.prototype._checkInputs.call(this);
  86915. this._quaternionCache.copyFrom(this.rotationQuaternion);
  86916. if (this._initialQuaternion) {
  86917. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86918. }
  86919. };
  86920. /**
  86921. * Reset the camera to its default orientation on the specified axis only.
  86922. * @param axis The axis to reset
  86923. */
  86924. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  86925. var _this = this;
  86926. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  86927. //can only work if this camera has a rotation quaternion already.
  86928. if (!this.rotationQuaternion)
  86929. return;
  86930. if (!this._initialQuaternion) {
  86931. this._initialQuaternion = new BABYLON.Quaternion();
  86932. }
  86933. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  86934. ['x', 'y', 'z'].forEach(function (axisName) {
  86935. if (!axis[axisName]) {
  86936. _this._initialQuaternion[axisName] = 0;
  86937. }
  86938. else {
  86939. _this._initialQuaternion[axisName] *= -1;
  86940. }
  86941. });
  86942. this._initialQuaternion.normalize();
  86943. //force rotation update
  86944. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86945. };
  86946. return DeviceOrientationCamera;
  86947. }(BABYLON.FreeCamera));
  86948. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  86949. })(BABYLON || (BABYLON = {}));
  86950. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  86951. var BABYLON;
  86952. (function (BABYLON) {
  86953. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  86954. __extends(VRDeviceOrientationFreeCamera, _super);
  86955. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86956. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86957. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86958. var _this = _super.call(this, name, position, scene) || this;
  86959. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86960. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86961. return _this;
  86962. }
  86963. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  86964. return "VRDeviceOrientationFreeCamera";
  86965. };
  86966. return VRDeviceOrientationFreeCamera;
  86967. }(BABYLON.DeviceOrientationCamera));
  86968. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  86969. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  86970. __extends(VRDeviceOrientationGamepadCamera, _super);
  86971. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86972. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86973. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86974. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  86975. _this.inputs.addGamepad();
  86976. return _this;
  86977. }
  86978. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  86979. return "VRDeviceOrientationGamepadCamera";
  86980. };
  86981. return VRDeviceOrientationGamepadCamera;
  86982. }(VRDeviceOrientationFreeCamera));
  86983. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  86984. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  86985. __extends(VRDeviceOrientationArcRotateCamera, _super);
  86986. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  86987. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86988. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86989. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86990. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86991. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86992. _this.inputs.addVRDeviceOrientation();
  86993. return _this;
  86994. }
  86995. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  86996. return "VRDeviceOrientationArcRotateCamera";
  86997. };
  86998. return VRDeviceOrientationArcRotateCamera;
  86999. }(BABYLON.ArcRotateCamera));
  87000. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87001. })(BABYLON || (BABYLON = {}));
  87002. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87003. var BABYLON;
  87004. (function (BABYLON) {
  87005. /**
  87006. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87007. */
  87008. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87009. __extends(AnaglyphFreeCamera, _super);
  87010. /**
  87011. * Creates a new AnaglyphFreeCamera
  87012. * @param name defines camera name
  87013. * @param position defines initial position
  87014. * @param interaxialDistance defines distance between each color axis
  87015. * @param scene defines the hosting scene
  87016. */
  87017. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87018. var _this = _super.call(this, name, position, scene) || this;
  87019. _this.interaxialDistance = interaxialDistance;
  87020. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87021. return _this;
  87022. }
  87023. /**
  87024. * Gets camera class name
  87025. * @returns AnaglyphFreeCamera
  87026. */
  87027. AnaglyphFreeCamera.prototype.getClassName = function () {
  87028. return "AnaglyphFreeCamera";
  87029. };
  87030. return AnaglyphFreeCamera;
  87031. }(BABYLON.FreeCamera));
  87032. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87033. /**
  87034. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87035. */
  87036. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87037. __extends(AnaglyphArcRotateCamera, _super);
  87038. /**
  87039. * Creates a new AnaglyphArcRotateCamera
  87040. * @param name defines camera name
  87041. * @param alpha defines alpha angle (in radians)
  87042. * @param beta defines beta angle (in radians)
  87043. * @param radius defines radius
  87044. * @param target defines camera target
  87045. * @param interaxialDistance defines distance between each color axis
  87046. * @param scene defines the hosting scene
  87047. */
  87048. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87049. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87050. _this.interaxialDistance = interaxialDistance;
  87051. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87052. return _this;
  87053. }
  87054. /**
  87055. * Gets camera class name
  87056. * @returns AnaglyphArcRotateCamera
  87057. */
  87058. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87059. return "AnaglyphArcRotateCamera";
  87060. };
  87061. return AnaglyphArcRotateCamera;
  87062. }(BABYLON.ArcRotateCamera));
  87063. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87064. /**
  87065. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87066. */
  87067. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87068. __extends(AnaglyphGamepadCamera, _super);
  87069. /**
  87070. * Creates a new AnaglyphGamepadCamera
  87071. * @param name defines camera name
  87072. * @param position defines initial position
  87073. * @param interaxialDistance defines distance between each color axis
  87074. * @param scene defines the hosting scene
  87075. */
  87076. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87077. var _this = _super.call(this, name, position, scene) || this;
  87078. _this.interaxialDistance = interaxialDistance;
  87079. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87080. return _this;
  87081. }
  87082. /**
  87083. * Gets camera class name
  87084. * @returns AnaglyphGamepadCamera
  87085. */
  87086. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87087. return "AnaglyphGamepadCamera";
  87088. };
  87089. return AnaglyphGamepadCamera;
  87090. }(BABYLON.GamepadCamera));
  87091. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87092. /**
  87093. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87094. */
  87095. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87096. __extends(AnaglyphUniversalCamera, _super);
  87097. /**
  87098. * Creates a new AnaglyphUniversalCamera
  87099. * @param name defines camera name
  87100. * @param position defines initial position
  87101. * @param interaxialDistance defines distance between each color axis
  87102. * @param scene defines the hosting scene
  87103. */
  87104. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87105. var _this = _super.call(this, name, position, scene) || this;
  87106. _this.interaxialDistance = interaxialDistance;
  87107. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87108. return _this;
  87109. }
  87110. /**
  87111. * Gets camera class name
  87112. * @returns AnaglyphUniversalCamera
  87113. */
  87114. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87115. return "AnaglyphUniversalCamera";
  87116. };
  87117. return AnaglyphUniversalCamera;
  87118. }(BABYLON.UniversalCamera));
  87119. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87120. /**
  87121. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87122. */
  87123. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87124. __extends(StereoscopicFreeCamera, _super);
  87125. /**
  87126. * Creates a new StereoscopicFreeCamera
  87127. * @param name defines camera name
  87128. * @param position defines initial position
  87129. * @param interaxialDistance defines distance between each color axis
  87130. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87131. * @param scene defines the hosting scene
  87132. */
  87133. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87134. var _this = _super.call(this, name, position, scene) || this;
  87135. _this.interaxialDistance = interaxialDistance;
  87136. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87137. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87138. return _this;
  87139. }
  87140. /**
  87141. * Gets camera class name
  87142. * @returns StereoscopicFreeCamera
  87143. */
  87144. StereoscopicFreeCamera.prototype.getClassName = function () {
  87145. return "StereoscopicFreeCamera";
  87146. };
  87147. return StereoscopicFreeCamera;
  87148. }(BABYLON.FreeCamera));
  87149. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87150. /**
  87151. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87152. */
  87153. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87154. __extends(StereoscopicArcRotateCamera, _super);
  87155. /**
  87156. * Creates a new StereoscopicArcRotateCamera
  87157. * @param name defines camera name
  87158. * @param alpha defines alpha angle (in radians)
  87159. * @param beta defines beta angle (in radians)
  87160. * @param radius defines radius
  87161. * @param target defines camera target
  87162. * @param interaxialDistance defines distance between each color axis
  87163. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87164. * @param scene defines the hosting scene
  87165. */
  87166. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87167. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87168. _this.interaxialDistance = interaxialDistance;
  87169. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87170. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87171. return _this;
  87172. }
  87173. /**
  87174. * Gets camera class name
  87175. * @returns StereoscopicArcRotateCamera
  87176. */
  87177. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87178. return "StereoscopicArcRotateCamera";
  87179. };
  87180. return StereoscopicArcRotateCamera;
  87181. }(BABYLON.ArcRotateCamera));
  87182. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87183. /**
  87184. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87185. */
  87186. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87187. __extends(StereoscopicGamepadCamera, _super);
  87188. /**
  87189. * Creates a new StereoscopicGamepadCamera
  87190. * @param name defines camera name
  87191. * @param position defines initial position
  87192. * @param interaxialDistance defines distance between each color axis
  87193. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87194. * @param scene defines the hosting scene
  87195. */
  87196. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87197. var _this = _super.call(this, name, position, scene) || this;
  87198. _this.interaxialDistance = interaxialDistance;
  87199. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87200. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87201. return _this;
  87202. }
  87203. /**
  87204. * Gets camera class name
  87205. * @returns StereoscopicGamepadCamera
  87206. */
  87207. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87208. return "StereoscopicGamepadCamera";
  87209. };
  87210. return StereoscopicGamepadCamera;
  87211. }(BABYLON.GamepadCamera));
  87212. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87213. /**
  87214. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87215. */
  87216. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87217. __extends(StereoscopicUniversalCamera, _super);
  87218. /**
  87219. * Creates a new StereoscopicUniversalCamera
  87220. * @param name defines camera name
  87221. * @param position defines initial position
  87222. * @param interaxialDistance defines distance between each color axis
  87223. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87224. * @param scene defines the hosting scene
  87225. */
  87226. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87227. var _this = _super.call(this, name, position, scene) || this;
  87228. _this.interaxialDistance = interaxialDistance;
  87229. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87230. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87231. return _this;
  87232. }
  87233. /**
  87234. * Gets camera class name
  87235. * @returns StereoscopicUniversalCamera
  87236. */
  87237. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87238. return "StereoscopicUniversalCamera";
  87239. };
  87240. return StereoscopicUniversalCamera;
  87241. }(BABYLON.UniversalCamera));
  87242. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87243. })(BABYLON || (BABYLON = {}));
  87244. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87245. var BABYLON;
  87246. (function (BABYLON) {
  87247. var VRExperienceHelperGazer = /** @class */ (function () {
  87248. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87249. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87250. this.scene = scene;
  87251. this._pointerDownOnMeshAsked = false;
  87252. this._isActionableMesh = false;
  87253. this._teleportationRequestInitiated = false;
  87254. this._teleportationBackRequestInitiated = false;
  87255. this._rotationRightAsked = false;
  87256. this._rotationLeftAsked = false;
  87257. this._dpadPressed = true;
  87258. this._activePointer = false;
  87259. this._id = VRExperienceHelperGazer._idCounter++;
  87260. // Gaze tracker
  87261. if (!gazeTrackerToClone) {
  87262. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87263. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87264. this._gazeTracker.isPickable = false;
  87265. this._gazeTracker.isVisible = false;
  87266. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87267. targetMat.specularColor = BABYLON.Color3.Black();
  87268. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87269. targetMat.backFaceCulling = false;
  87270. this._gazeTracker.material = targetMat;
  87271. }
  87272. else {
  87273. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87274. }
  87275. }
  87276. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87277. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87278. };
  87279. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87280. this._pointerDownOnMeshAsked = true;
  87281. if (this._currentMeshSelected && this._currentHit) {
  87282. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87283. }
  87284. };
  87285. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87286. if (this._currentMeshSelected && this._currentHit) {
  87287. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87288. }
  87289. this._pointerDownOnMeshAsked = false;
  87290. };
  87291. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87292. this._activePointer = true;
  87293. };
  87294. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87295. this._activePointer = false;
  87296. };
  87297. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87298. if (distance === void 0) { distance = 100; }
  87299. };
  87300. VRExperienceHelperGazer.prototype.dispose = function () {
  87301. this._interactionsEnabled = false;
  87302. this._teleportationEnabled = false;
  87303. if (this._gazeTracker) {
  87304. this._gazeTracker.dispose();
  87305. }
  87306. };
  87307. VRExperienceHelperGazer._idCounter = 0;
  87308. return VRExperienceHelperGazer;
  87309. }());
  87310. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87311. __extends(VRExperienceHelperControllerGazer, _super);
  87312. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87313. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87314. _this.webVRController = webVRController;
  87315. // Laser pointer
  87316. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87317. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87318. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87319. laserPointerMaterial.alpha = 0.6;
  87320. _this._laserPointer.material = laserPointerMaterial;
  87321. _this._laserPointer.rotation.x = Math.PI / 2;
  87322. _this._laserPointer.position.z = -0.5;
  87323. _this._laserPointer.isVisible = false;
  87324. if (!webVRController.mesh) {
  87325. // Create an empty mesh that is used prior to loading the high quality model
  87326. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87327. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87328. preloadPointerPose.rotation.x = -0.7;
  87329. preloadMesh.addChild(preloadPointerPose);
  87330. webVRController.attachToMesh(preloadMesh);
  87331. }
  87332. _this._setLaserPointerParent(webVRController.mesh);
  87333. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87334. _this._setLaserPointerParent(mesh);
  87335. });
  87336. return _this;
  87337. }
  87338. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87339. return this.webVRController.getForwardRay(length);
  87340. };
  87341. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87342. _super.prototype._activatePointer.call(this);
  87343. this._laserPointer.isVisible = true;
  87344. };
  87345. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87346. _super.prototype._deactivatePointer.call(this);
  87347. this._laserPointer.isVisible = false;
  87348. };
  87349. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87350. this._laserPointer.material.emissiveColor = color;
  87351. };
  87352. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87353. var makeNotPick = function (root) {
  87354. root.name += " laserPointer";
  87355. root.getChildMeshes().forEach(function (c) {
  87356. makeNotPick(c);
  87357. });
  87358. };
  87359. makeNotPick(mesh);
  87360. var childMeshes = mesh.getChildMeshes();
  87361. this.webVRController._pointingPoseNode = null;
  87362. for (var i = 0; i < childMeshes.length; i++) {
  87363. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87364. mesh = childMeshes[i];
  87365. this.webVRController._pointingPoseNode = mesh;
  87366. break;
  87367. }
  87368. }
  87369. this._laserPointer.parent = mesh;
  87370. };
  87371. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87372. if (distance === void 0) { distance = 100; }
  87373. this._laserPointer.scaling.y = distance;
  87374. this._laserPointer.position.z = -distance / 2;
  87375. };
  87376. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87377. _super.prototype.dispose.call(this);
  87378. this._laserPointer.dispose();
  87379. if (this._meshAttachedObserver) {
  87380. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87381. }
  87382. };
  87383. return VRExperienceHelperControllerGazer;
  87384. }(VRExperienceHelperGazer));
  87385. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87386. __extends(VRExperienceHelperCameraGazer, _super);
  87387. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87388. var _this = _super.call(this, scene) || this;
  87389. _this.getCamera = getCamera;
  87390. return _this;
  87391. }
  87392. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87393. var camera = this.getCamera();
  87394. if (camera) {
  87395. return camera.getForwardRay(length);
  87396. }
  87397. else {
  87398. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87399. }
  87400. };
  87401. return VRExperienceHelperCameraGazer;
  87402. }(VRExperienceHelperGazer));
  87403. /**
  87404. * Helps to quickly add VR support to an existing scene.
  87405. * See http://doc.babylonjs.com/how_to/webvr_helper
  87406. */
  87407. var VRExperienceHelper = /** @class */ (function () {
  87408. /**
  87409. * Instantiates a VRExperienceHelper.
  87410. * Helps to quickly add VR support to an existing scene.
  87411. * @param scene The scene the VRExperienceHelper belongs to.
  87412. * @param webVROptions Options to modify the vr experience helper's behavior.
  87413. */
  87414. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87415. if (webVROptions === void 0) { webVROptions = {}; }
  87416. var _this = this;
  87417. this.webVROptions = webVROptions;
  87418. // Can the system support WebVR, even if a headset isn't plugged in?
  87419. this._webVRsupported = false;
  87420. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87421. this._webVRready = false;
  87422. // Are we waiting for the requestPresent callback to complete?
  87423. this._webVRrequesting = false;
  87424. // Are we presenting to the headset right now?
  87425. this._webVRpresenting = false;
  87426. // Are we presenting in the fullscreen fallback?
  87427. this._fullscreenVRpresenting = false;
  87428. /**
  87429. * Observable raised when entering VR.
  87430. */
  87431. this.onEnteringVRObservable = new BABYLON.Observable();
  87432. /**
  87433. * Observable raised when exiting VR.
  87434. */
  87435. this.onExitingVRObservable = new BABYLON.Observable();
  87436. /**
  87437. * Observable raised when controller mesh is loaded.
  87438. */
  87439. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87440. this._useCustomVRButton = false;
  87441. this._teleportationRequested = false;
  87442. this._teleportActive = false;
  87443. this._floorMeshesCollection = [];
  87444. this._rotationAllowed = true;
  87445. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87446. this._isDefaultTeleportationTarget = true;
  87447. this._teleportationFillColor = "#444444";
  87448. this._teleportationBorderColor = "#FFFFFF";
  87449. this._rotationAngle = 0;
  87450. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87451. this._padSensibilityUp = 0.65;
  87452. this._padSensibilityDown = 0.35;
  87453. this.leftController = null;
  87454. this.rightController = null;
  87455. /**
  87456. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87457. */
  87458. this.onNewMeshSelected = new BABYLON.Observable();
  87459. /**
  87460. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87461. */
  87462. this.onNewMeshPicked = new BABYLON.Observable();
  87463. /**
  87464. * Observable raised before camera teleportation
  87465. */
  87466. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87467. /**
  87468. * Observable raised after camera teleportation
  87469. */
  87470. this.onAfterCameraTeleport = new BABYLON.Observable();
  87471. /**
  87472. * Observable raised when current selected mesh gets unselected
  87473. */
  87474. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87475. /**
  87476. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87477. */
  87478. this.teleportationEnabled = true;
  87479. this._teleportationInitialized = false;
  87480. this._interactionsEnabled = false;
  87481. this._interactionsRequested = false;
  87482. this._displayGaze = true;
  87483. this._displayLaserPointer = true;
  87484. this._onResize = function () {
  87485. _this.moveButtonToBottomRight();
  87486. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87487. _this.exitVR();
  87488. }
  87489. };
  87490. this._onFullscreenChange = function () {
  87491. if (document.fullscreen !== undefined) {
  87492. _this._fullscreenVRpresenting = document.fullscreen;
  87493. }
  87494. else if (document.mozFullScreen !== undefined) {
  87495. _this._fullscreenVRpresenting = document.mozFullScreen;
  87496. }
  87497. else if (document.webkitIsFullScreen !== undefined) {
  87498. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87499. }
  87500. else if (document.msIsFullScreen !== undefined) {
  87501. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87502. }
  87503. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87504. _this.exitVR();
  87505. if (!_this._useCustomVRButton) {
  87506. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87507. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87508. }
  87509. }
  87510. };
  87511. this.beforeRender = function () {
  87512. if (_this.leftController && _this.leftController._activePointer) {
  87513. _this._castRayAndSelectObject(_this.leftController);
  87514. }
  87515. if (_this.rightController && _this.rightController._activePointer) {
  87516. _this._castRayAndSelectObject(_this.rightController);
  87517. }
  87518. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87519. _this._castRayAndSelectObject(_this._cameraGazer);
  87520. }
  87521. else {
  87522. _this._cameraGazer._gazeTracker.isVisible = false;
  87523. }
  87524. };
  87525. this._onNewGamepadConnected = function (gamepad) {
  87526. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87527. if (gamepad.leftStick) {
  87528. gamepad.onleftstickchanged(function (stickValues) {
  87529. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87530. // Listening to classic/xbox gamepad only if no VR controller is active
  87531. if ((!_this.leftController && !_this.rightController) ||
  87532. ((_this.leftController && !_this.leftController._activePointer) &&
  87533. (_this.rightController && !_this.rightController._activePointer))) {
  87534. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87535. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87536. }
  87537. }
  87538. });
  87539. }
  87540. if (gamepad.rightStick) {
  87541. gamepad.onrightstickchanged(function (stickValues) {
  87542. if (_this._teleportationInitialized) {
  87543. _this._checkRotate(stickValues, _this._cameraGazer);
  87544. }
  87545. });
  87546. }
  87547. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87548. gamepad.onbuttondown(function (buttonPressed) {
  87549. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87550. _this._cameraGazer._selectionPointerDown();
  87551. }
  87552. });
  87553. gamepad.onbuttonup(function (buttonPressed) {
  87554. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87555. _this._cameraGazer._selectionPointerUp();
  87556. }
  87557. });
  87558. }
  87559. }
  87560. else {
  87561. var webVRController = gamepad;
  87562. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87563. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87564. _this.rightController = controller;
  87565. }
  87566. else {
  87567. _this.leftController = controller;
  87568. }
  87569. _this._tryEnableInteractionOnController(controller);
  87570. }
  87571. };
  87572. // 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
  87573. this._tryEnableInteractionOnController = function (controller) {
  87574. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87575. _this._enableInteractionOnController(controller);
  87576. }
  87577. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87578. _this._enableTeleportationOnController(controller);
  87579. }
  87580. };
  87581. this._onNewGamepadDisconnected = function (gamepad) {
  87582. if (gamepad instanceof BABYLON.WebVRController) {
  87583. if (gamepad.hand === "left" && _this.leftController != null) {
  87584. _this.leftController.dispose();
  87585. _this.leftController = null;
  87586. }
  87587. if (gamepad.hand === "right" && _this.rightController != null) {
  87588. _this.rightController.dispose();
  87589. _this.rightController = null;
  87590. }
  87591. }
  87592. };
  87593. this._workingVector = BABYLON.Vector3.Zero();
  87594. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87595. this._workingMatrix = BABYLON.Matrix.Identity();
  87596. this._scene = scene;
  87597. this._canvas = scene.getEngine().getRenderingCanvas();
  87598. // Parse options
  87599. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87600. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87601. }
  87602. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87603. webVROptions.createDeviceOrientationCamera = true;
  87604. }
  87605. if (webVROptions.defaultHeight === undefined) {
  87606. webVROptions.defaultHeight = 1.7;
  87607. }
  87608. if (webVROptions.useCustomVRButton) {
  87609. this._useCustomVRButton = true;
  87610. if (webVROptions.customVRButton) {
  87611. this._btnVR = webVROptions.customVRButton;
  87612. }
  87613. }
  87614. if (webVROptions.rayLength) {
  87615. this._rayLength = webVROptions.rayLength;
  87616. }
  87617. this._defaultHeight = webVROptions.defaultHeight;
  87618. if (webVROptions.positionScale) {
  87619. this._rayLength *= webVROptions.positionScale;
  87620. this._defaultHeight *= webVROptions.positionScale;
  87621. }
  87622. // Set position
  87623. if (this._scene.activeCamera) {
  87624. this._position = this._scene.activeCamera.position.clone();
  87625. }
  87626. else {
  87627. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87628. }
  87629. // Set non-vr camera
  87630. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87631. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87632. // Copy data from existing camera
  87633. if (this._scene.activeCamera) {
  87634. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87635. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87636. // Set rotation from previous camera
  87637. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87638. var targetCamera = this._scene.activeCamera;
  87639. if (targetCamera.rotationQuaternion) {
  87640. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87641. }
  87642. else {
  87643. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87644. }
  87645. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87646. }
  87647. }
  87648. this._scene.activeCamera = this._deviceOrientationCamera;
  87649. if (this._canvas) {
  87650. this._scene.activeCamera.attachControl(this._canvas);
  87651. }
  87652. }
  87653. else {
  87654. this._existingCamera = this._scene.activeCamera;
  87655. }
  87656. // Create VR cameras
  87657. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87658. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87659. }
  87660. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87661. this._webVRCamera.useStandingMatrix();
  87662. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87663. // Create default button
  87664. if (!this._useCustomVRButton) {
  87665. this._btnVR = document.createElement("BUTTON");
  87666. this._btnVR.className = "babylonVRicon";
  87667. this._btnVR.id = "babylonVRiconbtn";
  87668. this._btnVR.title = "Click to switch to VR";
  87669. 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) }";
  87670. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87671. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87672. // css += ".babylonVRicon.vrdisplaysupported { }";
  87673. // css += ".babylonVRicon.vrdisplayready { }";
  87674. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87675. var style = document.createElement('style');
  87676. style.appendChild(document.createTextNode(css));
  87677. document.getElementsByTagName('head')[0].appendChild(style);
  87678. this.moveButtonToBottomRight();
  87679. }
  87680. // VR button click event
  87681. if (this._btnVR) {
  87682. this._btnVR.addEventListener("click", function () {
  87683. if (!_this.isInVRMode) {
  87684. _this.enterVR();
  87685. }
  87686. else {
  87687. _this.exitVR();
  87688. }
  87689. });
  87690. }
  87691. // Window events
  87692. window.addEventListener("resize", this._onResize);
  87693. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87694. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87695. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87696. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87697. // Display vr button when headset is connected
  87698. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87699. this.displayVRButton();
  87700. }
  87701. else {
  87702. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87703. if (e.vrDisplay) {
  87704. _this.displayVRButton();
  87705. }
  87706. });
  87707. }
  87708. // Exiting VR mode using 'ESC' key on desktop
  87709. this._onKeyDown = function (event) {
  87710. if (event.keyCode === 27 && _this.isInVRMode) {
  87711. _this.exitVR();
  87712. }
  87713. };
  87714. document.addEventListener("keydown", this._onKeyDown);
  87715. // Exiting VR mode double tapping the touch screen
  87716. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87717. if (_this.isInVRMode) {
  87718. _this.exitVR();
  87719. if (_this._fullscreenVRpresenting) {
  87720. _this._scene.getEngine().switchFullscreen(true);
  87721. }
  87722. }
  87723. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87724. // Listen for WebVR display changes
  87725. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87726. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87727. this._onVRRequestPresentStart = function () {
  87728. _this._webVRrequesting = true;
  87729. _this.updateButtonVisibility();
  87730. };
  87731. this._onVRRequestPresentComplete = function (success) {
  87732. _this._webVRrequesting = false;
  87733. _this.updateButtonVisibility();
  87734. };
  87735. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87736. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87737. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87738. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87739. scene.onDisposeObservable.add(function () {
  87740. _this.dispose();
  87741. });
  87742. // Gamepad connection events
  87743. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87744. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87745. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87746. this.updateButtonVisibility();
  87747. //create easing functions
  87748. this._circleEase = new BABYLON.CircleEase();
  87749. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87750. }
  87751. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87752. /** Return this.onEnteringVRObservable
  87753. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87754. */
  87755. get: function () {
  87756. return this.onEnteringVRObservable;
  87757. },
  87758. enumerable: true,
  87759. configurable: true
  87760. });
  87761. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87762. /** Return this.onExitingVRObservable
  87763. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87764. */
  87765. get: function () {
  87766. return this.onExitingVRObservable;
  87767. },
  87768. enumerable: true,
  87769. configurable: true
  87770. });
  87771. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87772. /** Return this.onControllerMeshLoadedObservable
  87773. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87774. */
  87775. get: function () {
  87776. return this.onControllerMeshLoadedObservable;
  87777. },
  87778. enumerable: true,
  87779. configurable: true
  87780. });
  87781. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87782. /**
  87783. * The mesh used to display where the user is going to teleport.
  87784. */
  87785. get: function () {
  87786. return this._teleportationTarget;
  87787. },
  87788. /**
  87789. * Sets the mesh to be used to display where the user is going to teleport.
  87790. */
  87791. set: function (value) {
  87792. if (value) {
  87793. value.name = "teleportationTarget";
  87794. this._isDefaultTeleportationTarget = false;
  87795. this._teleportationTarget = value;
  87796. }
  87797. },
  87798. enumerable: true,
  87799. configurable: true
  87800. });
  87801. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87802. /**
  87803. * The mesh used to display where the user is selecting,
  87804. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87805. * See http://doc.babylonjs.com/resources/baking_transformations
  87806. */
  87807. get: function () {
  87808. return this._cameraGazer._gazeTracker;
  87809. },
  87810. set: function (value) {
  87811. if (value) {
  87812. this._cameraGazer._gazeTracker = value;
  87813. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87814. this._cameraGazer._gazeTracker.isPickable = false;
  87815. this._cameraGazer._gazeTracker.isVisible = false;
  87816. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87817. if (this.leftController) {
  87818. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87819. }
  87820. if (this.rightController) {
  87821. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87822. }
  87823. }
  87824. },
  87825. enumerable: true,
  87826. configurable: true
  87827. });
  87828. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87829. /**
  87830. * If the ray of the gaze should be displayed.
  87831. */
  87832. get: function () {
  87833. return this._displayGaze;
  87834. },
  87835. /**
  87836. * Sets if the ray of the gaze should be displayed.
  87837. */
  87838. set: function (value) {
  87839. this._displayGaze = value;
  87840. if (!value) {
  87841. this._cameraGazer._gazeTracker.isVisible = false;
  87842. if (this.leftController) {
  87843. this.leftController._gazeTracker.isVisible = false;
  87844. }
  87845. if (this.rightController) {
  87846. this.rightController._gazeTracker.isVisible = false;
  87847. }
  87848. }
  87849. },
  87850. enumerable: true,
  87851. configurable: true
  87852. });
  87853. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87854. /**
  87855. * If the ray of the LaserPointer should be displayed.
  87856. */
  87857. get: function () {
  87858. return this._displayLaserPointer;
  87859. },
  87860. /**
  87861. * Sets if the ray of the LaserPointer should be displayed.
  87862. */
  87863. set: function (value) {
  87864. this._displayLaserPointer = value;
  87865. if (!value) {
  87866. if (this.rightController) {
  87867. this.rightController._deactivatePointer();
  87868. this.rightController._gazeTracker.isVisible = false;
  87869. }
  87870. if (this.leftController) {
  87871. this.leftController._deactivatePointer();
  87872. this.leftController._gazeTracker.isVisible = false;
  87873. }
  87874. }
  87875. else {
  87876. if (this.rightController) {
  87877. this.rightController._activatePointer();
  87878. }
  87879. if (this.leftController) {
  87880. this.leftController._activatePointer();
  87881. }
  87882. }
  87883. },
  87884. enumerable: true,
  87885. configurable: true
  87886. });
  87887. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87888. /**
  87889. * The deviceOrientationCamera used as the camera when not in VR.
  87890. */
  87891. get: function () {
  87892. return this._deviceOrientationCamera;
  87893. },
  87894. enumerable: true,
  87895. configurable: true
  87896. });
  87897. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87898. /**
  87899. * Based on the current WebVR support, returns the current VR camera used.
  87900. */
  87901. get: function () {
  87902. if (this._webVRready) {
  87903. return this._webVRCamera;
  87904. }
  87905. else {
  87906. return this._scene.activeCamera;
  87907. }
  87908. },
  87909. enumerable: true,
  87910. configurable: true
  87911. });
  87912. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  87913. /**
  87914. * The webVRCamera which is used when in VR.
  87915. */
  87916. get: function () {
  87917. return this._webVRCamera;
  87918. },
  87919. enumerable: true,
  87920. configurable: true
  87921. });
  87922. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  87923. /**
  87924. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  87925. */
  87926. get: function () {
  87927. return this._vrDeviceOrientationCamera;
  87928. },
  87929. enumerable: true,
  87930. configurable: true
  87931. });
  87932. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  87933. get: function () {
  87934. var result = this._cameraGazer._teleportationRequestInitiated
  87935. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  87936. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  87937. return result;
  87938. },
  87939. enumerable: true,
  87940. configurable: true
  87941. });
  87942. // Raised when one of the controller has loaded successfully its associated default mesh
  87943. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  87944. if (this.leftController && this.leftController.webVRController == webVRController) {
  87945. if (webVRController.mesh) {
  87946. this.leftController._setLaserPointerParent(webVRController.mesh);
  87947. }
  87948. }
  87949. if (this.rightController && this.rightController.webVRController == webVRController) {
  87950. if (webVRController.mesh) {
  87951. this.rightController._setLaserPointerParent(webVRController.mesh);
  87952. }
  87953. }
  87954. try {
  87955. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  87956. }
  87957. catch (err) {
  87958. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  87959. }
  87960. };
  87961. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  87962. /**
  87963. * Gets a value indicating if we are currently in VR mode.
  87964. */
  87965. get: function () {
  87966. return this._webVRpresenting || this._fullscreenVRpresenting;
  87967. },
  87968. enumerable: true,
  87969. configurable: true
  87970. });
  87971. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  87972. var vrDisplay = this._scene.getEngine().getVRDevice();
  87973. if (vrDisplay) {
  87974. var wasPresenting = this._webVRpresenting;
  87975. // A VR display is connected
  87976. this._webVRpresenting = vrDisplay.isPresenting;
  87977. if (wasPresenting && !this._webVRpresenting)
  87978. this.exitVR();
  87979. }
  87980. else {
  87981. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  87982. }
  87983. this.updateButtonVisibility();
  87984. };
  87985. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  87986. this._webVRsupported = eventArgs.vrSupported;
  87987. this._webVRready = !!eventArgs.vrDisplay;
  87988. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  87989. this.updateButtonVisibility();
  87990. };
  87991. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  87992. if (this._canvas && !this._useCustomVRButton) {
  87993. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  87994. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  87995. }
  87996. };
  87997. VRExperienceHelper.prototype.displayVRButton = function () {
  87998. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  87999. document.body.appendChild(this._btnVR);
  88000. this._btnVRDisplayed = true;
  88001. }
  88002. };
  88003. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88004. if (!this._btnVR || this._useCustomVRButton) {
  88005. return;
  88006. }
  88007. this._btnVR.className = "babylonVRicon";
  88008. if (this.isInVRMode) {
  88009. this._btnVR.className += " vrdisplaypresenting";
  88010. }
  88011. else {
  88012. if (this._webVRready)
  88013. this._btnVR.className += " vrdisplayready";
  88014. if (this._webVRsupported)
  88015. this._btnVR.className += " vrdisplaysupported";
  88016. if (this._webVRrequesting)
  88017. this._btnVR.className += " vrdisplayrequesting";
  88018. }
  88019. };
  88020. /**
  88021. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88022. * Otherwise, will use the fullscreen API.
  88023. */
  88024. VRExperienceHelper.prototype.enterVR = function () {
  88025. if (this.onEnteringVRObservable) {
  88026. try {
  88027. this.onEnteringVRObservable.notifyObservers(this);
  88028. }
  88029. catch (err) {
  88030. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88031. }
  88032. }
  88033. if (this._scene.activeCamera) {
  88034. this._position = this._scene.activeCamera.position.clone();
  88035. // make sure that we return to the last active camera
  88036. this._existingCamera = this._scene.activeCamera;
  88037. }
  88038. if (this._webVRrequesting)
  88039. return;
  88040. // If WebVR is supported and a headset is connected
  88041. if (this._webVRready) {
  88042. if (!this._webVRpresenting) {
  88043. this._webVRCamera.position = this._position;
  88044. this._scene.activeCamera = this._webVRCamera;
  88045. }
  88046. }
  88047. else if (this._vrDeviceOrientationCamera) {
  88048. this._vrDeviceOrientationCamera.position = this._position;
  88049. if (this._scene.activeCamera) {
  88050. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88051. }
  88052. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88053. this._scene.getEngine().switchFullscreen(true);
  88054. this.updateButtonVisibility();
  88055. }
  88056. if (this._scene.activeCamera && this._canvas) {
  88057. this._scene.activeCamera.attachControl(this._canvas);
  88058. }
  88059. if (this._interactionsEnabled) {
  88060. this._scene.registerBeforeRender(this.beforeRender);
  88061. }
  88062. };
  88063. /**
  88064. * Attempt to exit VR, or fullscreen.
  88065. */
  88066. VRExperienceHelper.prototype.exitVR = function () {
  88067. if (this.onExitingVRObservable) {
  88068. try {
  88069. this.onExitingVRObservable.notifyObservers(this);
  88070. }
  88071. catch (err) {
  88072. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88073. }
  88074. }
  88075. if (this._webVRpresenting) {
  88076. this._scene.getEngine().disableVR();
  88077. }
  88078. if (this._scene.activeCamera) {
  88079. this._position = this._scene.activeCamera.position.clone();
  88080. }
  88081. if (this._deviceOrientationCamera) {
  88082. this._deviceOrientationCamera.position = this._position;
  88083. this._scene.activeCamera = this._deviceOrientationCamera;
  88084. if (this._canvas) {
  88085. this._scene.activeCamera.attachControl(this._canvas);
  88086. }
  88087. }
  88088. else if (this._existingCamera) {
  88089. this._existingCamera.position = this._position;
  88090. this._scene.activeCamera = this._existingCamera;
  88091. }
  88092. this.updateButtonVisibility();
  88093. if (this._interactionsEnabled) {
  88094. this._scene.unregisterBeforeRender(this.beforeRender);
  88095. }
  88096. // resize to update width and height when exiting vr exits fullscreen
  88097. this._scene.getEngine().resize();
  88098. };
  88099. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88100. /**
  88101. * The position of the vr experience helper.
  88102. */
  88103. get: function () {
  88104. return this._position;
  88105. },
  88106. /**
  88107. * Sets the position of the vr experience helper.
  88108. */
  88109. set: function (value) {
  88110. this._position = value;
  88111. if (this._scene.activeCamera) {
  88112. this._scene.activeCamera.position = value;
  88113. }
  88114. },
  88115. enumerable: true,
  88116. configurable: true
  88117. });
  88118. /**
  88119. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88120. */
  88121. VRExperienceHelper.prototype.enableInteractions = function () {
  88122. var _this = this;
  88123. if (!this._interactionsEnabled) {
  88124. this._interactionsRequested = true;
  88125. if (this.leftController) {
  88126. this._enableInteractionOnController(this.leftController);
  88127. }
  88128. if (this.rightController) {
  88129. this._enableInteractionOnController(this.rightController);
  88130. }
  88131. this.raySelectionPredicate = function (mesh) {
  88132. return mesh.isVisible;
  88133. };
  88134. this.meshSelectionPredicate = function (mesh) {
  88135. return true;
  88136. };
  88137. this._raySelectionPredicate = function (mesh) {
  88138. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88139. && mesh.name.indexOf("teleportationTarget") === -1
  88140. && mesh.name.indexOf("torusTeleportation") === -1
  88141. && mesh.name.indexOf("laserPointer") === -1)) {
  88142. return _this.raySelectionPredicate(mesh);
  88143. }
  88144. return false;
  88145. };
  88146. this._interactionsEnabled = true;
  88147. }
  88148. };
  88149. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88150. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88151. if (this._floorMeshesCollection[i].id === mesh.id) {
  88152. return true;
  88153. }
  88154. }
  88155. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88156. return true;
  88157. }
  88158. return false;
  88159. };
  88160. /**
  88161. * Adds a floor mesh to be used for teleportation.
  88162. * @param floorMesh the mesh to be used for teleportation.
  88163. */
  88164. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88165. if (!this._floorMeshesCollection) {
  88166. return;
  88167. }
  88168. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88169. return;
  88170. }
  88171. this._floorMeshesCollection.push(floorMesh);
  88172. };
  88173. /**
  88174. * Removes a floor mesh from being used for teleportation.
  88175. * @param floorMesh the mesh to be removed.
  88176. */
  88177. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88178. if (!this._floorMeshesCollection) {
  88179. return;
  88180. }
  88181. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88182. if (meshIndex !== -1) {
  88183. this._floorMeshesCollection.splice(meshIndex, 1);
  88184. }
  88185. };
  88186. /**
  88187. * Enables interactions and teleportation using the VR controllers and gaze.
  88188. * @param vrTeleportationOptions options to modify teleportation behavior.
  88189. */
  88190. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88191. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88192. if (!this._teleportationInitialized) {
  88193. this._teleportationRequested = true;
  88194. this.enableInteractions();
  88195. if (vrTeleportationOptions.floorMeshName) {
  88196. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88197. }
  88198. if (vrTeleportationOptions.floorMeshes) {
  88199. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88200. }
  88201. if (this.leftController != null) {
  88202. this._enableTeleportationOnController(this.leftController);
  88203. }
  88204. if (this.rightController != null) {
  88205. this._enableTeleportationOnController(this.rightController);
  88206. }
  88207. // Creates an image processing post process for the vignette not relying
  88208. // on the main scene configuration for image processing to reduce setup and spaces
  88209. // (gamma/linear) conflicts.
  88210. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88211. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88212. imageProcessingConfiguration.vignetteEnabled = true;
  88213. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88214. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88215. this._teleportationInitialized = true;
  88216. if (this._isDefaultTeleportationTarget) {
  88217. this._createTeleportationCircles();
  88218. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88219. }
  88220. }
  88221. };
  88222. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88223. var _this = this;
  88224. var controllerMesh = controller.webVRController.mesh;
  88225. if (controllerMesh) {
  88226. controller._interactionsEnabled = true;
  88227. controller._activatePointer();
  88228. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88229. // Enabling / disabling laserPointer
  88230. if (_this._displayLaserPointer && stateObject.value === 1) {
  88231. if (controller._activePointer) {
  88232. controller._deactivatePointer();
  88233. }
  88234. else {
  88235. controller._activatePointer();
  88236. }
  88237. if (_this.displayGaze) {
  88238. controller._gazeTracker.isVisible = controller._activePointer;
  88239. }
  88240. }
  88241. });
  88242. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88243. if (!controller._pointerDownOnMeshAsked) {
  88244. if (stateObject.value > _this._padSensibilityUp) {
  88245. controller._selectionPointerDown();
  88246. }
  88247. }
  88248. else if (stateObject.value < _this._padSensibilityDown) {
  88249. controller._selectionPointerUp();
  88250. }
  88251. });
  88252. }
  88253. };
  88254. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88255. // Dont teleport if another gaze already requested teleportation
  88256. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88257. return;
  88258. }
  88259. if (!gazer._teleportationRequestInitiated) {
  88260. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88261. gazer._activatePointer();
  88262. gazer._teleportationRequestInitiated = true;
  88263. }
  88264. }
  88265. else {
  88266. // Listening to the proper controller values changes to confirm teleportation
  88267. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88268. if (this._teleportActive) {
  88269. this._teleportCamera(this._haloCenter);
  88270. }
  88271. gazer._teleportationRequestInitiated = false;
  88272. }
  88273. }
  88274. };
  88275. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88276. // Only rotate when user is not currently selecting a teleportation location
  88277. if (gazer._teleportationRequestInitiated) {
  88278. return;
  88279. }
  88280. if (!gazer._rotationLeftAsked) {
  88281. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88282. gazer._rotationLeftAsked = true;
  88283. if (this._rotationAllowed) {
  88284. this._rotateCamera(false);
  88285. }
  88286. }
  88287. }
  88288. else {
  88289. if (stateObject.x > -this._padSensibilityDown) {
  88290. gazer._rotationLeftAsked = false;
  88291. }
  88292. }
  88293. if (!gazer._rotationRightAsked) {
  88294. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88295. gazer._rotationRightAsked = true;
  88296. if (this._rotationAllowed) {
  88297. this._rotateCamera(true);
  88298. }
  88299. }
  88300. }
  88301. else {
  88302. if (stateObject.x < this._padSensibilityDown) {
  88303. gazer._rotationRightAsked = false;
  88304. }
  88305. }
  88306. };
  88307. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88308. // Only teleport backwards when user is not currently selecting a teleportation location
  88309. if (gazer._teleportationRequestInitiated) {
  88310. return;
  88311. }
  88312. // Teleport backwards
  88313. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88314. if (!gazer._teleportationBackRequestInitiated) {
  88315. if (!this.currentVRCamera) {
  88316. return;
  88317. }
  88318. // Get rotation and position of the current camera
  88319. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88320. var position = this.currentVRCamera.position;
  88321. // If the camera has device position, use that instead
  88322. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88323. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88324. position = this.currentVRCamera.devicePosition;
  88325. }
  88326. // Get matrix with only the y rotation of the device rotation
  88327. rotation.toEulerAnglesToRef(this._workingVector);
  88328. this._workingVector.z = 0;
  88329. this._workingVector.x = 0;
  88330. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88331. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88332. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88333. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88334. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88335. var ray = new BABYLON.Ray(position, this._workingVector);
  88336. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88337. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88338. this._teleportCamera(hit.pickedPoint);
  88339. }
  88340. gazer._teleportationBackRequestInitiated = true;
  88341. }
  88342. }
  88343. else {
  88344. gazer._teleportationBackRequestInitiated = false;
  88345. }
  88346. };
  88347. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88348. var _this = this;
  88349. var controllerMesh = controller.webVRController.mesh;
  88350. if (controllerMesh) {
  88351. if (!controller._interactionsEnabled) {
  88352. this._enableInteractionOnController(controller);
  88353. }
  88354. controller._interactionsEnabled = true;
  88355. controller._teleportationEnabled = true;
  88356. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88357. controller._dpadPressed = false;
  88358. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88359. controller._dpadPressed = stateObject.pressed;
  88360. if (!controller._dpadPressed) {
  88361. controller._rotationLeftAsked = false;
  88362. controller._rotationRightAsked = false;
  88363. controller._teleportationBackRequestInitiated = false;
  88364. }
  88365. });
  88366. }
  88367. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88368. if (_this.teleportationEnabled) {
  88369. _this._checkTeleportBackwards(stateObject, controller);
  88370. _this._checkTeleportWithRay(stateObject, controller);
  88371. }
  88372. _this._checkRotate(stateObject, controller);
  88373. });
  88374. }
  88375. };
  88376. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88377. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88378. this._teleportationTarget.isPickable = false;
  88379. var length = 512;
  88380. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88381. dynamicTexture.hasAlpha = true;
  88382. var context = dynamicTexture.getContext();
  88383. var centerX = length / 2;
  88384. var centerY = length / 2;
  88385. var radius = 200;
  88386. context.beginPath();
  88387. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88388. context.fillStyle = this._teleportationFillColor;
  88389. context.fill();
  88390. context.lineWidth = 10;
  88391. context.strokeStyle = this._teleportationBorderColor;
  88392. context.stroke();
  88393. context.closePath();
  88394. dynamicTexture.update();
  88395. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88396. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88397. this._teleportationTarget.material = teleportationCircleMaterial;
  88398. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88399. torus.isPickable = false;
  88400. torus.parent = this._teleportationTarget;
  88401. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88402. var keys = [];
  88403. keys.push({
  88404. frame: 0,
  88405. value: 0
  88406. });
  88407. keys.push({
  88408. frame: 30,
  88409. value: 0.4
  88410. });
  88411. keys.push({
  88412. frame: 60,
  88413. value: 0
  88414. });
  88415. animationInnerCircle.setKeys(keys);
  88416. var easingFunction = new BABYLON.SineEase();
  88417. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88418. animationInnerCircle.setEasingFunction(easingFunction);
  88419. torus.animations = [];
  88420. torus.animations.push(animationInnerCircle);
  88421. this._scene.beginAnimation(torus, 0, 60, true);
  88422. this._hideTeleportationTarget();
  88423. };
  88424. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88425. this._teleportActive = true;
  88426. if (this._teleportationInitialized) {
  88427. this._teleportationTarget.isVisible = true;
  88428. if (this._isDefaultTeleportationTarget) {
  88429. this._teleportationTarget.getChildren()[0].isVisible = true;
  88430. }
  88431. }
  88432. };
  88433. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88434. this._teleportActive = false;
  88435. if (this._teleportationInitialized) {
  88436. this._teleportationTarget.isVisible = false;
  88437. if (this._isDefaultTeleportationTarget) {
  88438. this._teleportationTarget.getChildren()[0].isVisible = false;
  88439. }
  88440. }
  88441. };
  88442. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88443. var _this = this;
  88444. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88445. return;
  88446. }
  88447. if (right) {
  88448. this._rotationAngle++;
  88449. }
  88450. else {
  88451. this._rotationAngle--;
  88452. }
  88453. this.currentVRCamera.animations = [];
  88454. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88455. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88456. var animationRotationKeys = [];
  88457. animationRotationKeys.push({
  88458. frame: 0,
  88459. value: this.currentVRCamera.rotationQuaternion
  88460. });
  88461. animationRotationKeys.push({
  88462. frame: 6,
  88463. value: target
  88464. });
  88465. animationRotation.setKeys(animationRotationKeys);
  88466. animationRotation.setEasingFunction(this._circleEase);
  88467. this.currentVRCamera.animations.push(animationRotation);
  88468. this._postProcessMove.animations = [];
  88469. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88470. var vignetteWeightKeys = [];
  88471. vignetteWeightKeys.push({
  88472. frame: 0,
  88473. value: 0
  88474. });
  88475. vignetteWeightKeys.push({
  88476. frame: 3,
  88477. value: 4
  88478. });
  88479. vignetteWeightKeys.push({
  88480. frame: 6,
  88481. value: 0
  88482. });
  88483. animationPP.setKeys(vignetteWeightKeys);
  88484. animationPP.setEasingFunction(this._circleEase);
  88485. this._postProcessMove.animations.push(animationPP);
  88486. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88487. var vignetteStretchKeys = [];
  88488. vignetteStretchKeys.push({
  88489. frame: 0,
  88490. value: 0
  88491. });
  88492. vignetteStretchKeys.push({
  88493. frame: 3,
  88494. value: 10
  88495. });
  88496. vignetteStretchKeys.push({
  88497. frame: 6,
  88498. value: 0
  88499. });
  88500. animationPP2.setKeys(vignetteStretchKeys);
  88501. animationPP2.setEasingFunction(this._circleEase);
  88502. this._postProcessMove.animations.push(animationPP2);
  88503. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88504. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88505. this._postProcessMove.samples = 4;
  88506. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88507. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88508. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88509. });
  88510. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88511. };
  88512. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88513. if (hit.pickedPoint) {
  88514. if (gazer._teleportationRequestInitiated) {
  88515. this._displayTeleportationTarget();
  88516. this._haloCenter.copyFrom(hit.pickedPoint);
  88517. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88518. }
  88519. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88520. if (pickNormal) {
  88521. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88522. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88523. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88524. }
  88525. this._teleportationTarget.position.y += 0.1;
  88526. }
  88527. };
  88528. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88529. var _this = this;
  88530. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88531. return;
  88532. }
  88533. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88534. // offset of the headset from the anchor.
  88535. if (this.webVRCamera.leftCamera) {
  88536. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88537. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88538. location.subtractToRef(this._workingVector, this._workingVector);
  88539. }
  88540. else {
  88541. this._workingVector.copyFrom(location);
  88542. }
  88543. // Add height to account for user's height offset
  88544. if (this.isInVRMode) {
  88545. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88546. }
  88547. else {
  88548. this._workingVector.y += this._defaultHeight;
  88549. }
  88550. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88551. // Create animation from the camera's position to the new location
  88552. this.currentVRCamera.animations = [];
  88553. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88554. var animationCameraTeleportationKeys = [{
  88555. frame: 0,
  88556. value: this.currentVRCamera.position
  88557. },
  88558. {
  88559. frame: 11,
  88560. value: this._workingVector
  88561. }
  88562. ];
  88563. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88564. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88565. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88566. this._postProcessMove.animations = [];
  88567. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88568. var vignetteWeightKeys = [];
  88569. vignetteWeightKeys.push({
  88570. frame: 0,
  88571. value: 0
  88572. });
  88573. vignetteWeightKeys.push({
  88574. frame: 5,
  88575. value: 8
  88576. });
  88577. vignetteWeightKeys.push({
  88578. frame: 11,
  88579. value: 0
  88580. });
  88581. animationPP.setKeys(vignetteWeightKeys);
  88582. this._postProcessMove.animations.push(animationPP);
  88583. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88584. var vignetteStretchKeys = [];
  88585. vignetteStretchKeys.push({
  88586. frame: 0,
  88587. value: 0
  88588. });
  88589. vignetteStretchKeys.push({
  88590. frame: 5,
  88591. value: 10
  88592. });
  88593. vignetteStretchKeys.push({
  88594. frame: 11,
  88595. value: 0
  88596. });
  88597. animationPP2.setKeys(vignetteStretchKeys);
  88598. this._postProcessMove.animations.push(animationPP2);
  88599. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88600. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88601. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88602. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88603. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88604. });
  88605. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88606. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88607. });
  88608. this._hideTeleportationTarget();
  88609. };
  88610. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88611. if (normal) {
  88612. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88613. if (angle < Math.PI / 2) {
  88614. normal.scaleInPlace(-1);
  88615. }
  88616. }
  88617. return normal;
  88618. };
  88619. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88620. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88621. return;
  88622. }
  88623. var ray = gazer._getForwardRay(this._rayLength);
  88624. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88625. // Moving the gazeTracker on the mesh face targetted
  88626. if (hit && hit.pickedPoint) {
  88627. if (this._displayGaze) {
  88628. var multiplier = 1;
  88629. gazer._gazeTracker.isVisible = true;
  88630. if (gazer._isActionableMesh) {
  88631. multiplier = 3;
  88632. }
  88633. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88634. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88635. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88636. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88637. // To avoid z-fighting
  88638. var deltaFighting = 0.002;
  88639. if (pickNormal) {
  88640. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88641. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88642. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88643. }
  88644. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88645. if (gazer._gazeTracker.position.x < 0) {
  88646. gazer._gazeTracker.position.x += deltaFighting;
  88647. }
  88648. else {
  88649. gazer._gazeTracker.position.x -= deltaFighting;
  88650. }
  88651. if (gazer._gazeTracker.position.y < 0) {
  88652. gazer._gazeTracker.position.y += deltaFighting;
  88653. }
  88654. else {
  88655. gazer._gazeTracker.position.y -= deltaFighting;
  88656. }
  88657. if (gazer._gazeTracker.position.z < 0) {
  88658. gazer._gazeTracker.position.z += deltaFighting;
  88659. }
  88660. else {
  88661. gazer._gazeTracker.position.z -= deltaFighting;
  88662. }
  88663. }
  88664. // Changing the size of the laser pointer based on the distance from the targetted point
  88665. gazer._updatePointerDistance(hit.distance);
  88666. }
  88667. else {
  88668. gazer._updatePointerDistance();
  88669. gazer._gazeTracker.isVisible = false;
  88670. }
  88671. if (hit && hit.pickedMesh) {
  88672. gazer._currentHit = hit;
  88673. if (gazer._pointerDownOnMeshAsked) {
  88674. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88675. }
  88676. // The object selected is the floor, we're in a teleportation scenario
  88677. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88678. // Moving the teleportation area to this targetted point
  88679. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88680. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88681. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88682. }
  88683. gazer._currentMeshSelected = null;
  88684. if (gazer._teleportationRequestInitiated) {
  88685. this._moveTeleportationSelectorTo(hit, gazer, ray);
  88686. }
  88687. return;
  88688. }
  88689. // If not, we're in a selection scenario
  88690. //this._teleportationAllowed = false;
  88691. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88692. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88693. this.onNewMeshPicked.notifyObservers(hit);
  88694. gazer._currentMeshSelected = hit.pickedMesh;
  88695. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88696. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88697. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88698. gazer._isActionableMesh = true;
  88699. }
  88700. else {
  88701. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88702. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88703. gazer._isActionableMesh = false;
  88704. }
  88705. try {
  88706. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88707. }
  88708. catch (err) {
  88709. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88710. }
  88711. }
  88712. else {
  88713. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88714. gazer._currentMeshSelected = null;
  88715. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88716. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88717. }
  88718. }
  88719. }
  88720. else {
  88721. gazer._currentHit = null;
  88722. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88723. gazer._currentMeshSelected = null;
  88724. //this._teleportationAllowed = false;
  88725. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88726. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88727. }
  88728. };
  88729. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88730. if (mesh) {
  88731. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88732. }
  88733. };
  88734. /**
  88735. * Sets the color of the laser ray from the vr controllers.
  88736. * @param color new color for the ray.
  88737. */
  88738. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88739. if (this.leftController) {
  88740. this.leftController._setLaserPointerColor(color);
  88741. }
  88742. if (this.rightController) {
  88743. this.rightController._setLaserPointerColor(color);
  88744. }
  88745. };
  88746. /**
  88747. * Sets the color of the ray from the vr headsets gaze.
  88748. * @param color new color for the ray.
  88749. */
  88750. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88751. if (!this._cameraGazer._gazeTracker.material) {
  88752. return;
  88753. }
  88754. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88755. if (this.leftController) {
  88756. this.leftController._gazeTracker.material.emissiveColor = color;
  88757. }
  88758. if (this.rightController) {
  88759. this.rightController._gazeTracker.material.emissiveColor = color;
  88760. }
  88761. };
  88762. /**
  88763. * Exits VR and disposes of the vr experience helper
  88764. */
  88765. VRExperienceHelper.prototype.dispose = function () {
  88766. if (this.isInVRMode) {
  88767. this.exitVR();
  88768. }
  88769. if (this._postProcessMove) {
  88770. this._postProcessMove.dispose();
  88771. }
  88772. if (this._webVRCamera) {
  88773. this._webVRCamera.dispose();
  88774. }
  88775. if (this._vrDeviceOrientationCamera) {
  88776. this._vrDeviceOrientationCamera.dispose();
  88777. }
  88778. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88779. document.body.removeChild(this._btnVR);
  88780. }
  88781. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88782. this._deviceOrientationCamera.dispose();
  88783. }
  88784. if (this._cameraGazer) {
  88785. this._cameraGazer.dispose();
  88786. }
  88787. if (this.leftController) {
  88788. this.leftController.dispose();
  88789. }
  88790. if (this.rightController) {
  88791. this.rightController.dispose();
  88792. }
  88793. if (this._teleportationTarget) {
  88794. this._teleportationTarget.dispose();
  88795. }
  88796. this._floorMeshesCollection = [];
  88797. document.removeEventListener("keydown", this._onKeyDown);
  88798. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88799. window.removeEventListener("resize", this._onResize);
  88800. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88801. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88802. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88803. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88804. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88805. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88806. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88807. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88808. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88809. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88810. this._scene.unregisterBeforeRender(this.beforeRender);
  88811. };
  88812. /**
  88813. * Gets the name of the VRExperienceHelper class
  88814. * @returns "VRExperienceHelper"
  88815. */
  88816. VRExperienceHelper.prototype.getClassName = function () {
  88817. return "VRExperienceHelper";
  88818. };
  88819. return VRExperienceHelper;
  88820. }());
  88821. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88822. })(BABYLON || (BABYLON = {}));
  88823. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88824. // Mainly based on these 2 articles :
  88825. // 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
  88826. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88827. var BABYLON;
  88828. (function (BABYLON) {
  88829. /**
  88830. * Defines the potential axis of a Joystick
  88831. */
  88832. var JoystickAxis;
  88833. (function (JoystickAxis) {
  88834. /** X axis */
  88835. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88836. /** Y axis */
  88837. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88838. /** Z axis */
  88839. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88840. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88841. /**
  88842. * Class used to define virtual joystick (used in touch mode)
  88843. */
  88844. var VirtualJoystick = /** @class */ (function () {
  88845. /**
  88846. * Creates a new virtual joystick
  88847. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88848. */
  88849. function VirtualJoystick(leftJoystick) {
  88850. var _this = this;
  88851. if (leftJoystick) {
  88852. this._leftJoystick = true;
  88853. }
  88854. else {
  88855. this._leftJoystick = false;
  88856. }
  88857. VirtualJoystick._globalJoystickIndex++;
  88858. // By default left & right arrow keys are moving the X
  88859. // and up & down keys are moving the Y
  88860. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88861. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88862. this.reverseLeftRight = false;
  88863. this.reverseUpDown = false;
  88864. // collections of pointers
  88865. this._touches = new BABYLON.StringDictionary();
  88866. this.deltaPosition = BABYLON.Vector3.Zero();
  88867. this._joystickSensibility = 25;
  88868. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88869. this._onResize = function (evt) {
  88870. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88871. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88872. if (VirtualJoystick.vjCanvas) {
  88873. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88874. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88875. }
  88876. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88877. };
  88878. // injecting a canvas element on top of the canvas 3D game
  88879. if (!VirtualJoystick.vjCanvas) {
  88880. window.addEventListener("resize", this._onResize, false);
  88881. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88882. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88883. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88884. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88885. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88886. VirtualJoystick.vjCanvas.style.width = "100%";
  88887. VirtualJoystick.vjCanvas.style.height = "100%";
  88888. VirtualJoystick.vjCanvas.style.position = "absolute";
  88889. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88890. VirtualJoystick.vjCanvas.style.top = "0px";
  88891. VirtualJoystick.vjCanvas.style.left = "0px";
  88892. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88893. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88894. // Support for jQuery PEP polyfill
  88895. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88896. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88897. if (!context) {
  88898. throw new Error("Unable to create canvas for virtual joystick");
  88899. }
  88900. VirtualJoystick.vjCanvasContext = context;
  88901. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  88902. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88903. document.body.appendChild(VirtualJoystick.vjCanvas);
  88904. }
  88905. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  88906. this.pressed = false;
  88907. // default joystick color
  88908. this._joystickColor = "cyan";
  88909. this._joystickPointerID = -1;
  88910. // current joystick position
  88911. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  88912. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  88913. // origin joystick position
  88914. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  88915. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  88916. this._onPointerDownHandlerRef = function (evt) {
  88917. _this._onPointerDown(evt);
  88918. };
  88919. this._onPointerMoveHandlerRef = function (evt) {
  88920. _this._onPointerMove(evt);
  88921. };
  88922. this._onPointerUpHandlerRef = function (evt) {
  88923. _this._onPointerUp(evt);
  88924. };
  88925. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  88926. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  88927. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  88928. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  88929. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  88930. evt.preventDefault(); // Disables system menu
  88931. }, false);
  88932. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88933. }
  88934. /**
  88935. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  88936. * @param newJoystickSensibility defines the new sensibility
  88937. */
  88938. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  88939. this._joystickSensibility = newJoystickSensibility;
  88940. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88941. };
  88942. VirtualJoystick.prototype._onPointerDown = function (e) {
  88943. var positionOnScreenCondition;
  88944. e.preventDefault();
  88945. if (this._leftJoystick === true) {
  88946. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  88947. }
  88948. else {
  88949. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  88950. }
  88951. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  88952. // First contact will be dedicated to the virtual joystick
  88953. this._joystickPointerID = e.pointerId;
  88954. this._joystickPointerStartPos.x = e.clientX;
  88955. this._joystickPointerStartPos.y = e.clientY;
  88956. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  88957. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  88958. this._deltaJoystickVector.x = 0;
  88959. this._deltaJoystickVector.y = 0;
  88960. this.pressed = true;
  88961. this._touches.add(e.pointerId.toString(), e);
  88962. }
  88963. else {
  88964. // You can only trigger the action buttons with a joystick declared
  88965. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  88966. this._action();
  88967. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  88968. }
  88969. }
  88970. };
  88971. VirtualJoystick.prototype._onPointerMove = function (e) {
  88972. // If the current pointer is the one associated to the joystick (first touch contact)
  88973. if (this._joystickPointerID == e.pointerId) {
  88974. this._joystickPointerPos.x = e.clientX;
  88975. this._joystickPointerPos.y = e.clientY;
  88976. this._deltaJoystickVector = this._joystickPointerPos.clone();
  88977. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  88978. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  88979. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  88980. switch (this._axisTargetedByLeftAndRight) {
  88981. case JoystickAxis.X:
  88982. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  88983. break;
  88984. case JoystickAxis.Y:
  88985. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  88986. break;
  88987. case JoystickAxis.Z:
  88988. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  88989. break;
  88990. }
  88991. var directionUpDown = this.reverseUpDown ? 1 : -1;
  88992. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  88993. switch (this._axisTargetedByUpAndDown) {
  88994. case JoystickAxis.X:
  88995. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  88996. break;
  88997. case JoystickAxis.Y:
  88998. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  88999. break;
  89000. case JoystickAxis.Z:
  89001. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89002. break;
  89003. }
  89004. }
  89005. else {
  89006. var data = this._touches.get(e.pointerId.toString());
  89007. if (data) {
  89008. data.x = e.clientX;
  89009. data.y = e.clientY;
  89010. }
  89011. }
  89012. };
  89013. VirtualJoystick.prototype._onPointerUp = function (e) {
  89014. if (this._joystickPointerID == e.pointerId) {
  89015. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89016. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89017. this._joystickPointerID = -1;
  89018. this.pressed = false;
  89019. }
  89020. else {
  89021. var touch = this._touches.get(e.pointerId.toString());
  89022. if (touch) {
  89023. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89024. }
  89025. }
  89026. this._deltaJoystickVector.x = 0;
  89027. this._deltaJoystickVector.y = 0;
  89028. this._touches.remove(e.pointerId.toString());
  89029. };
  89030. /**
  89031. * Change the color of the virtual joystick
  89032. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89033. */
  89034. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89035. this._joystickColor = newColor;
  89036. };
  89037. /**
  89038. * Defines a callback to call when the joystick is touched
  89039. * @param action defines the callback
  89040. */
  89041. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89042. this._action = action;
  89043. };
  89044. /**
  89045. * Defines which axis you'd like to control for left & right
  89046. * @param axis defines the axis to use
  89047. */
  89048. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89049. switch (axis) {
  89050. case JoystickAxis.X:
  89051. case JoystickAxis.Y:
  89052. case JoystickAxis.Z:
  89053. this._axisTargetedByLeftAndRight = axis;
  89054. break;
  89055. default:
  89056. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89057. break;
  89058. }
  89059. };
  89060. /**
  89061. * Defines which axis you'd like to control for up & down
  89062. * @param axis defines the axis to use
  89063. */
  89064. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89065. switch (axis) {
  89066. case JoystickAxis.X:
  89067. case JoystickAxis.Y:
  89068. case JoystickAxis.Z:
  89069. this._axisTargetedByUpAndDown = axis;
  89070. break;
  89071. default:
  89072. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89073. break;
  89074. }
  89075. };
  89076. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89077. var _this = this;
  89078. if (this.pressed) {
  89079. this._touches.forEach(function (key, touch) {
  89080. if (touch.pointerId === _this._joystickPointerID) {
  89081. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89082. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89083. VirtualJoystick.vjCanvasContext.beginPath();
  89084. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89085. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89086. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89087. VirtualJoystick.vjCanvasContext.stroke();
  89088. VirtualJoystick.vjCanvasContext.closePath();
  89089. VirtualJoystick.vjCanvasContext.beginPath();
  89090. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89091. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89092. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89093. VirtualJoystick.vjCanvasContext.stroke();
  89094. VirtualJoystick.vjCanvasContext.closePath();
  89095. VirtualJoystick.vjCanvasContext.beginPath();
  89096. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89097. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89098. VirtualJoystick.vjCanvasContext.stroke();
  89099. VirtualJoystick.vjCanvasContext.closePath();
  89100. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89101. }
  89102. else {
  89103. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89104. VirtualJoystick.vjCanvasContext.beginPath();
  89105. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89106. VirtualJoystick.vjCanvasContext.beginPath();
  89107. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89108. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89109. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89110. VirtualJoystick.vjCanvasContext.stroke();
  89111. VirtualJoystick.vjCanvasContext.closePath();
  89112. touch.prevX = touch.x;
  89113. touch.prevY = touch.y;
  89114. }
  89115. ;
  89116. });
  89117. }
  89118. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89119. };
  89120. /**
  89121. * Release internal HTML canvas
  89122. */
  89123. VirtualJoystick.prototype.releaseCanvas = function () {
  89124. if (VirtualJoystick.vjCanvas) {
  89125. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89126. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89127. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89128. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89129. window.removeEventListener("resize", this._onResize);
  89130. document.body.removeChild(VirtualJoystick.vjCanvas);
  89131. VirtualJoystick.vjCanvas = null;
  89132. }
  89133. };
  89134. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89135. VirtualJoystick._globalJoystickIndex = 0;
  89136. return VirtualJoystick;
  89137. }());
  89138. BABYLON.VirtualJoystick = VirtualJoystick;
  89139. })(BABYLON || (BABYLON = {}));
  89140. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89141. var BABYLON;
  89142. (function (BABYLON) {
  89143. // We're mainly based on the logic defined into the FreeCamera code
  89144. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89145. __extends(VirtualJoysticksCamera, _super);
  89146. function VirtualJoysticksCamera(name, position, scene) {
  89147. var _this = _super.call(this, name, position, scene) || this;
  89148. _this.inputs.addVirtualJoystick();
  89149. return _this;
  89150. }
  89151. VirtualJoysticksCamera.prototype.getClassName = function () {
  89152. return "VirtualJoysticksCamera";
  89153. };
  89154. return VirtualJoysticksCamera;
  89155. }(BABYLON.FreeCamera));
  89156. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89157. })(BABYLON || (BABYLON = {}));
  89158. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89159. var BABYLON;
  89160. (function (BABYLON) {
  89161. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89162. function FreeCameraVirtualJoystickInput() {
  89163. }
  89164. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89165. return this._leftjoystick;
  89166. };
  89167. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89168. return this._rightjoystick;
  89169. };
  89170. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89171. if (this._leftjoystick) {
  89172. var camera = this.camera;
  89173. var speed = camera._computeLocalCameraSpeed() * 50;
  89174. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89175. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89176. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89177. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89178. if (!this._leftjoystick.pressed) {
  89179. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89180. }
  89181. if (!this._rightjoystick.pressed) {
  89182. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89183. }
  89184. }
  89185. };
  89186. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89187. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89188. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89189. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89190. this._leftjoystick.setJoystickSensibility(0.15);
  89191. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89192. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89193. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89194. this._rightjoystick.reverseUpDown = true;
  89195. this._rightjoystick.setJoystickSensibility(0.05);
  89196. this._rightjoystick.setJoystickColor("yellow");
  89197. };
  89198. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89199. this._leftjoystick.releaseCanvas();
  89200. this._rightjoystick.releaseCanvas();
  89201. };
  89202. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89203. return "FreeCameraVirtualJoystickInput";
  89204. };
  89205. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89206. return "virtualJoystick";
  89207. };
  89208. return FreeCameraVirtualJoystickInput;
  89209. }());
  89210. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89211. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89212. })(BABYLON || (BABYLON = {}));
  89213. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89214. var BABYLON;
  89215. (function (BABYLON) {
  89216. var SimplificationSettings = /** @class */ (function () {
  89217. function SimplificationSettings(quality, distance, optimizeMesh) {
  89218. this.quality = quality;
  89219. this.distance = distance;
  89220. this.optimizeMesh = optimizeMesh;
  89221. }
  89222. return SimplificationSettings;
  89223. }());
  89224. BABYLON.SimplificationSettings = SimplificationSettings;
  89225. var SimplificationQueue = /** @class */ (function () {
  89226. function SimplificationQueue() {
  89227. this.running = false;
  89228. this._simplificationArray = [];
  89229. }
  89230. SimplificationQueue.prototype.addTask = function (task) {
  89231. this._simplificationArray.push(task);
  89232. };
  89233. SimplificationQueue.prototype.executeNext = function () {
  89234. var task = this._simplificationArray.pop();
  89235. if (task) {
  89236. this.running = true;
  89237. this.runSimplification(task);
  89238. }
  89239. else {
  89240. this.running = false;
  89241. }
  89242. };
  89243. SimplificationQueue.prototype.runSimplification = function (task) {
  89244. var _this = this;
  89245. if (task.parallelProcessing) {
  89246. //parallel simplifier
  89247. task.settings.forEach(function (setting) {
  89248. var simplifier = _this.getSimplifier(task);
  89249. simplifier.simplify(setting, function (newMesh) {
  89250. task.mesh.addLODLevel(setting.distance, newMesh);
  89251. newMesh.isVisible = true;
  89252. //check if it is the last
  89253. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89254. //all done, run the success callback.
  89255. task.successCallback();
  89256. }
  89257. _this.executeNext();
  89258. });
  89259. });
  89260. }
  89261. else {
  89262. //single simplifier.
  89263. var simplifier = this.getSimplifier(task);
  89264. var runDecimation = function (setting, callback) {
  89265. simplifier.simplify(setting, function (newMesh) {
  89266. task.mesh.addLODLevel(setting.distance, newMesh);
  89267. newMesh.isVisible = true;
  89268. //run the next quality level
  89269. callback();
  89270. });
  89271. };
  89272. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89273. runDecimation(task.settings[loop.index], function () {
  89274. loop.executeNext();
  89275. });
  89276. }, function () {
  89277. //execution ended, run the success callback.
  89278. if (task.successCallback) {
  89279. task.successCallback();
  89280. }
  89281. _this.executeNext();
  89282. });
  89283. }
  89284. };
  89285. SimplificationQueue.prototype.getSimplifier = function (task) {
  89286. switch (task.simplificationType) {
  89287. case SimplificationType.QUADRATIC:
  89288. default:
  89289. return new QuadraticErrorSimplification(task.mesh);
  89290. }
  89291. };
  89292. return SimplificationQueue;
  89293. }());
  89294. BABYLON.SimplificationQueue = SimplificationQueue;
  89295. /**
  89296. * The implemented types of simplification
  89297. * At the moment only Quadratic Error Decimation is implemented
  89298. */
  89299. var SimplificationType;
  89300. (function (SimplificationType) {
  89301. /** Quadratic error decimation */
  89302. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89303. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89304. var DecimationTriangle = /** @class */ (function () {
  89305. function DecimationTriangle(vertices) {
  89306. this.vertices = vertices;
  89307. this.error = new Array(4);
  89308. this.deleted = false;
  89309. this.isDirty = false;
  89310. this.deletePending = false;
  89311. this.borderFactor = 0;
  89312. }
  89313. return DecimationTriangle;
  89314. }());
  89315. BABYLON.DecimationTriangle = DecimationTriangle;
  89316. var DecimationVertex = /** @class */ (function () {
  89317. function DecimationVertex(position, id) {
  89318. this.position = position;
  89319. this.id = id;
  89320. this.isBorder = true;
  89321. this.q = new QuadraticMatrix();
  89322. this.triangleCount = 0;
  89323. this.triangleStart = 0;
  89324. this.originalOffsets = [];
  89325. }
  89326. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89327. this.position.copyFrom(newPosition);
  89328. };
  89329. return DecimationVertex;
  89330. }());
  89331. BABYLON.DecimationVertex = DecimationVertex;
  89332. var QuadraticMatrix = /** @class */ (function () {
  89333. function QuadraticMatrix(data) {
  89334. this.data = new Array(10);
  89335. for (var i = 0; i < 10; ++i) {
  89336. if (data && data[i]) {
  89337. this.data[i] = data[i];
  89338. }
  89339. else {
  89340. this.data[i] = 0;
  89341. }
  89342. }
  89343. }
  89344. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89345. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89346. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89347. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89348. return det;
  89349. };
  89350. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89351. for (var i = 0; i < 10; ++i) {
  89352. this.data[i] += matrix.data[i];
  89353. }
  89354. };
  89355. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89356. for (var i = 0; i < 10; ++i) {
  89357. this.data[i] += data[i];
  89358. }
  89359. };
  89360. QuadraticMatrix.prototype.add = function (matrix) {
  89361. var m = new QuadraticMatrix();
  89362. for (var i = 0; i < 10; ++i) {
  89363. m.data[i] = this.data[i] + matrix.data[i];
  89364. }
  89365. return m;
  89366. };
  89367. QuadraticMatrix.FromData = function (a, b, c, d) {
  89368. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89369. };
  89370. //returning an array to avoid garbage collection
  89371. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89372. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89373. };
  89374. return QuadraticMatrix;
  89375. }());
  89376. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89377. var Reference = /** @class */ (function () {
  89378. function Reference(vertexId, triangleId) {
  89379. this.vertexId = vertexId;
  89380. this.triangleId = triangleId;
  89381. }
  89382. return Reference;
  89383. }());
  89384. BABYLON.Reference = Reference;
  89385. /**
  89386. * An implementation of the Quadratic Error simplification algorithm.
  89387. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89388. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89389. * @author RaananW
  89390. */
  89391. var QuadraticErrorSimplification = /** @class */ (function () {
  89392. function QuadraticErrorSimplification(_mesh) {
  89393. this._mesh = _mesh;
  89394. this.syncIterations = 5000;
  89395. this.aggressiveness = 7;
  89396. this.decimationIterations = 100;
  89397. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89398. }
  89399. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89400. var _this = this;
  89401. this.initDecimatedMesh();
  89402. //iterating through the submeshes array, one after the other.
  89403. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89404. _this.initWithMesh(loop.index, function () {
  89405. _this.runDecimation(settings, loop.index, function () {
  89406. loop.executeNext();
  89407. });
  89408. }, settings.optimizeMesh);
  89409. }, function () {
  89410. setTimeout(function () {
  89411. successCallback(_this._reconstructedMesh);
  89412. }, 0);
  89413. });
  89414. };
  89415. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89416. var _this = this;
  89417. var targetCount = ~~(this.triangles.length * settings.quality);
  89418. var deletedTriangles = 0;
  89419. var triangleCount = this.triangles.length;
  89420. var iterationFunction = function (iteration, callback) {
  89421. setTimeout(function () {
  89422. if (iteration % 5 === 0) {
  89423. _this.updateMesh(iteration === 0);
  89424. }
  89425. for (var i = 0; i < _this.triangles.length; ++i) {
  89426. _this.triangles[i].isDirty = false;
  89427. }
  89428. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89429. var trianglesIterator = function (i) {
  89430. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89431. var t = _this.triangles[tIdx];
  89432. if (!t)
  89433. return;
  89434. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89435. return;
  89436. }
  89437. for (var j = 0; j < 3; ++j) {
  89438. if (t.error[j] < threshold) {
  89439. var deleted0 = [];
  89440. var deleted1 = [];
  89441. var v0 = t.vertices[j];
  89442. var v1 = t.vertices[(j + 1) % 3];
  89443. if (v0.isBorder || v1.isBorder)
  89444. continue;
  89445. var p = BABYLON.Vector3.Zero();
  89446. var n = BABYLON.Vector3.Zero();
  89447. var uv = BABYLON.Vector2.Zero();
  89448. var color = new BABYLON.Color4(0, 0, 0, 1);
  89449. _this.calculateError(v0, v1, p, n, uv, color);
  89450. var delTr = new Array();
  89451. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89452. continue;
  89453. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89454. continue;
  89455. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89456. continue;
  89457. var uniqueArray = new Array();
  89458. delTr.forEach(function (deletedT) {
  89459. if (uniqueArray.indexOf(deletedT) === -1) {
  89460. deletedT.deletePending = true;
  89461. uniqueArray.push(deletedT);
  89462. }
  89463. });
  89464. if (uniqueArray.length % 2 !== 0) {
  89465. continue;
  89466. }
  89467. v0.q = v1.q.add(v0.q);
  89468. v0.updatePosition(p);
  89469. var tStart = _this.references.length;
  89470. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89471. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89472. var tCount = _this.references.length - tStart;
  89473. if (tCount <= v0.triangleCount) {
  89474. if (tCount) {
  89475. for (var c = 0; c < tCount; c++) {
  89476. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89477. }
  89478. }
  89479. }
  89480. else {
  89481. v0.triangleStart = tStart;
  89482. }
  89483. v0.triangleCount = tCount;
  89484. break;
  89485. }
  89486. }
  89487. };
  89488. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89489. }, 0);
  89490. };
  89491. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89492. if (triangleCount - deletedTriangles <= targetCount)
  89493. loop.breakLoop();
  89494. else {
  89495. iterationFunction(loop.index, function () {
  89496. loop.executeNext();
  89497. });
  89498. }
  89499. }, function () {
  89500. setTimeout(function () {
  89501. //reconstruct this part of the mesh
  89502. _this.reconstructMesh(submeshIndex);
  89503. successCallback();
  89504. }, 0);
  89505. });
  89506. };
  89507. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89508. var _this = this;
  89509. this.vertices = [];
  89510. this.triangles = [];
  89511. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89512. var indices = this._mesh.getIndices();
  89513. var submesh = this._mesh.subMeshes[submeshIndex];
  89514. var findInVertices = function (positionToSearch) {
  89515. if (optimizeMesh) {
  89516. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89517. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89518. return _this.vertices[ii];
  89519. }
  89520. }
  89521. }
  89522. return null;
  89523. };
  89524. var vertexReferences = [];
  89525. var vertexInit = function (i) {
  89526. if (!positionData) {
  89527. return;
  89528. }
  89529. var offset = i + submesh.verticesStart;
  89530. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89531. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89532. vertex.originalOffsets.push(offset);
  89533. if (vertex.id === _this.vertices.length) {
  89534. _this.vertices.push(vertex);
  89535. }
  89536. vertexReferences.push(vertex.id);
  89537. };
  89538. //var totalVertices = mesh.getTotalVertices();
  89539. var totalVertices = submesh.verticesCount;
  89540. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89541. var indicesInit = function (i) {
  89542. if (!indices) {
  89543. return;
  89544. }
  89545. var offset = (submesh.indexStart / 3) + i;
  89546. var pos = (offset * 3);
  89547. var i0 = indices[pos + 0];
  89548. var i1 = indices[pos + 1];
  89549. var i2 = indices[pos + 2];
  89550. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89551. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89552. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89553. var triangle = new DecimationTriangle([v0, v1, v2]);
  89554. triangle.originalOffset = pos;
  89555. _this.triangles.push(triangle);
  89556. };
  89557. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89558. _this.init(callback);
  89559. });
  89560. });
  89561. };
  89562. QuadraticErrorSimplification.prototype.init = function (callback) {
  89563. var _this = this;
  89564. var triangleInit1 = function (i) {
  89565. var t = _this.triangles[i];
  89566. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89567. for (var j = 0; j < 3; j++) {
  89568. 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))));
  89569. }
  89570. };
  89571. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89572. var triangleInit2 = function (i) {
  89573. var t = _this.triangles[i];
  89574. for (var j = 0; j < 3; ++j) {
  89575. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89576. }
  89577. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89578. };
  89579. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89580. callback();
  89581. });
  89582. });
  89583. };
  89584. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89585. var newTriangles = [];
  89586. var i;
  89587. for (i = 0; i < this.vertices.length; ++i) {
  89588. this.vertices[i].triangleCount = 0;
  89589. }
  89590. var t;
  89591. var j;
  89592. for (i = 0; i < this.triangles.length; ++i) {
  89593. if (!this.triangles[i].deleted) {
  89594. t = this.triangles[i];
  89595. for (j = 0; j < 3; ++j) {
  89596. t.vertices[j].triangleCount = 1;
  89597. }
  89598. newTriangles.push(t);
  89599. }
  89600. }
  89601. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89602. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89603. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89604. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89605. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89606. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89607. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89608. var vertexCount = 0;
  89609. for (i = 0; i < this.vertices.length; ++i) {
  89610. var vertex = this.vertices[i];
  89611. vertex.id = vertexCount;
  89612. if (vertex.triangleCount) {
  89613. vertex.originalOffsets.forEach(function (originalOffset) {
  89614. if (!normalData) {
  89615. return;
  89616. }
  89617. newPositionData.push(vertex.position.x);
  89618. newPositionData.push(vertex.position.y);
  89619. newPositionData.push(vertex.position.z);
  89620. newNormalData.push(normalData[originalOffset * 3]);
  89621. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89622. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89623. if (uvs && uvs.length) {
  89624. newUVsData.push(uvs[(originalOffset * 2)]);
  89625. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89626. }
  89627. else if (colorsData && colorsData.length) {
  89628. newColorsData.push(colorsData[(originalOffset * 4)]);
  89629. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89630. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89631. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89632. }
  89633. ++vertexCount;
  89634. });
  89635. }
  89636. }
  89637. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89638. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89639. var submeshesArray = this._reconstructedMesh.subMeshes;
  89640. this._reconstructedMesh.subMeshes = [];
  89641. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89642. var originalIndices = this._mesh.getIndices();
  89643. for (i = 0; i < newTriangles.length; ++i) {
  89644. t = newTriangles[i]; //now get the new referencing point for each vertex
  89645. [0, 1, 2].forEach(function (idx) {
  89646. var id = originalIndices[t.originalOffset + idx];
  89647. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89648. if (offset < 0)
  89649. offset = 0;
  89650. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89651. });
  89652. }
  89653. //overwriting the old vertex buffers and indices.
  89654. this._reconstructedMesh.setIndices(newIndicesArray);
  89655. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89656. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89657. if (newUVsData.length > 0)
  89658. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89659. if (newColorsData.length > 0)
  89660. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89661. //create submesh
  89662. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89663. if (submeshIndex > 0) {
  89664. this._reconstructedMesh.subMeshes = [];
  89665. submeshesArray.forEach(function (submesh) {
  89666. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89667. });
  89668. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89669. }
  89670. };
  89671. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89672. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89673. this._reconstructedMesh.material = this._mesh.material;
  89674. this._reconstructedMesh.parent = this._mesh.parent;
  89675. this._reconstructedMesh.isVisible = false;
  89676. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89677. };
  89678. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89679. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89680. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89681. if (t.deleted)
  89682. continue;
  89683. var s = this.references[vertex1.triangleStart + i].vertexId;
  89684. var v1 = t.vertices[(s + 1) % 3];
  89685. var v2 = t.vertices[(s + 2) % 3];
  89686. if ((v1 === vertex2 || v2 === vertex2)) {
  89687. deletedArray[i] = true;
  89688. delTr.push(t);
  89689. continue;
  89690. }
  89691. var d1 = v1.position.subtract(point);
  89692. d1 = d1.normalize();
  89693. var d2 = v2.position.subtract(point);
  89694. d2 = d2.normalize();
  89695. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89696. return true;
  89697. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89698. deletedArray[i] = false;
  89699. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89700. return true;
  89701. }
  89702. return false;
  89703. };
  89704. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89705. var newDeleted = deletedTriangles;
  89706. for (var i = 0; i < vertex.triangleCount; ++i) {
  89707. var ref = this.references[vertex.triangleStart + i];
  89708. var t = this.triangles[ref.triangleId];
  89709. if (t.deleted)
  89710. continue;
  89711. if (deletedArray[i] && t.deletePending) {
  89712. t.deleted = true;
  89713. newDeleted++;
  89714. continue;
  89715. }
  89716. t.vertices[ref.vertexId] = origVertex;
  89717. t.isDirty = true;
  89718. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89719. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89720. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89721. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89722. this.references.push(ref);
  89723. }
  89724. return newDeleted;
  89725. };
  89726. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89727. for (var i = 0; i < this.vertices.length; ++i) {
  89728. var vCount = [];
  89729. var vId = [];
  89730. var v = this.vertices[i];
  89731. var j;
  89732. for (j = 0; j < v.triangleCount; ++j) {
  89733. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89734. for (var ii = 0; ii < 3; ii++) {
  89735. var ofs = 0;
  89736. var vv = triangle.vertices[ii];
  89737. while (ofs < vCount.length) {
  89738. if (vId[ofs] === vv.id)
  89739. break;
  89740. ++ofs;
  89741. }
  89742. if (ofs === vCount.length) {
  89743. vCount.push(1);
  89744. vId.push(vv.id);
  89745. }
  89746. else {
  89747. vCount[ofs]++;
  89748. }
  89749. }
  89750. }
  89751. for (j = 0; j < vCount.length; ++j) {
  89752. if (vCount[j] === 1) {
  89753. this.vertices[vId[j]].isBorder = true;
  89754. }
  89755. else {
  89756. this.vertices[vId[j]].isBorder = false;
  89757. }
  89758. }
  89759. }
  89760. };
  89761. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89762. if (identifyBorders === void 0) { identifyBorders = false; }
  89763. var i;
  89764. if (!identifyBorders) {
  89765. var newTrianglesVector = [];
  89766. for (i = 0; i < this.triangles.length; ++i) {
  89767. if (!this.triangles[i].deleted) {
  89768. newTrianglesVector.push(this.triangles[i]);
  89769. }
  89770. }
  89771. this.triangles = newTrianglesVector;
  89772. }
  89773. for (i = 0; i < this.vertices.length; ++i) {
  89774. this.vertices[i].triangleCount = 0;
  89775. this.vertices[i].triangleStart = 0;
  89776. }
  89777. var t;
  89778. var j;
  89779. var v;
  89780. for (i = 0; i < this.triangles.length; ++i) {
  89781. t = this.triangles[i];
  89782. for (j = 0; j < 3; ++j) {
  89783. v = t.vertices[j];
  89784. v.triangleCount++;
  89785. }
  89786. }
  89787. var tStart = 0;
  89788. for (i = 0; i < this.vertices.length; ++i) {
  89789. this.vertices[i].triangleStart = tStart;
  89790. tStart += this.vertices[i].triangleCount;
  89791. this.vertices[i].triangleCount = 0;
  89792. }
  89793. var newReferences = new Array(this.triangles.length * 3);
  89794. for (i = 0; i < this.triangles.length; ++i) {
  89795. t = this.triangles[i];
  89796. for (j = 0; j < 3; ++j) {
  89797. v = t.vertices[j];
  89798. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89799. v.triangleCount++;
  89800. }
  89801. }
  89802. this.references = newReferences;
  89803. if (identifyBorders) {
  89804. this.identifyBorder();
  89805. }
  89806. };
  89807. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89808. var x = point.x;
  89809. var y = point.y;
  89810. var z = point.z;
  89811. 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
  89812. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89813. };
  89814. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89815. var q = vertex1.q.add(vertex2.q);
  89816. var border = vertex1.isBorder && vertex2.isBorder;
  89817. var error = 0;
  89818. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89819. if (qDet !== 0 && !border) {
  89820. if (!pointResult) {
  89821. pointResult = BABYLON.Vector3.Zero();
  89822. }
  89823. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89824. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89825. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89826. error = this.vertexError(q, pointResult);
  89827. }
  89828. else {
  89829. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89830. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89831. var error1 = this.vertexError(q, vertex1.position);
  89832. var error2 = this.vertexError(q, vertex2.position);
  89833. var error3 = this.vertexError(q, p3);
  89834. error = Math.min(error1, error2, error3);
  89835. if (error === error1) {
  89836. if (pointResult) {
  89837. pointResult.copyFrom(vertex1.position);
  89838. }
  89839. }
  89840. else if (error === error2) {
  89841. if (pointResult) {
  89842. pointResult.copyFrom(vertex2.position);
  89843. }
  89844. }
  89845. else {
  89846. if (pointResult) {
  89847. pointResult.copyFrom(p3);
  89848. }
  89849. }
  89850. }
  89851. return error;
  89852. };
  89853. return QuadraticErrorSimplification;
  89854. }());
  89855. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89856. })(BABYLON || (BABYLON = {}));
  89857. //# sourceMappingURL=babylon.meshSimplification.js.map
  89858. var BABYLON;
  89859. (function (BABYLON) {
  89860. var MeshLODLevel = /** @class */ (function () {
  89861. function MeshLODLevel(distance, mesh) {
  89862. this.distance = distance;
  89863. this.mesh = mesh;
  89864. }
  89865. return MeshLODLevel;
  89866. }());
  89867. BABYLON.MeshLODLevel = MeshLODLevel;
  89868. })(BABYLON || (BABYLON = {}));
  89869. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89870. var BABYLON;
  89871. (function (BABYLON) {
  89872. /**
  89873. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89874. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89875. */
  89876. var SceneOptimization = /** @class */ (function () {
  89877. /**
  89878. * Creates the SceneOptimization object
  89879. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89880. * @param desc defines the description associated with the optimization
  89881. */
  89882. function SceneOptimization(
  89883. /**
  89884. * Defines the priority of this optimization (0 by default which means first in the list)
  89885. */
  89886. priority) {
  89887. if (priority === void 0) { priority = 0; }
  89888. this.priority = priority;
  89889. }
  89890. /**
  89891. * Gets a string describing the action executed by the current optimization
  89892. * @returns description string
  89893. */
  89894. SceneOptimization.prototype.getDescription = function () {
  89895. return "";
  89896. };
  89897. /**
  89898. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89899. * @param scene defines the current scene where to apply this optimization
  89900. * @param optimizer defines the current optimizer
  89901. * @returns true if everything that can be done was applied
  89902. */
  89903. SceneOptimization.prototype.apply = function (scene, optimizer) {
  89904. return true;
  89905. };
  89906. ;
  89907. return SceneOptimization;
  89908. }());
  89909. BABYLON.SceneOptimization = SceneOptimization;
  89910. /**
  89911. * Defines an optimization used to reduce the size of render target textures
  89912. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89913. */
  89914. var TextureOptimization = /** @class */ (function (_super) {
  89915. __extends(TextureOptimization, _super);
  89916. /**
  89917. * Creates the TextureOptimization object
  89918. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89919. * @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
  89920. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89921. */
  89922. function TextureOptimization(
  89923. /**
  89924. * Defines the priority of this optimization (0 by default which means first in the list)
  89925. */
  89926. priority,
  89927. /**
  89928. * 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
  89929. */
  89930. maximumSize,
  89931. /**
  89932. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89933. */
  89934. step) {
  89935. if (priority === void 0) { priority = 0; }
  89936. if (maximumSize === void 0) { maximumSize = 1024; }
  89937. if (step === void 0) { step = 0.5; }
  89938. var _this = _super.call(this, priority) || this;
  89939. _this.priority = priority;
  89940. _this.maximumSize = maximumSize;
  89941. _this.step = step;
  89942. return _this;
  89943. }
  89944. /**
  89945. * Gets a string describing the action executed by the current optimization
  89946. * @returns description string
  89947. */
  89948. TextureOptimization.prototype.getDescription = function () {
  89949. return "Reducing render target texture size to " + this.maximumSize;
  89950. };
  89951. /**
  89952. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89953. * @param scene defines the current scene where to apply this optimization
  89954. * @param optimizer defines the current optimizer
  89955. * @returns true if everything that can be done was applied
  89956. */
  89957. TextureOptimization.prototype.apply = function (scene, optimizer) {
  89958. var allDone = true;
  89959. for (var index = 0; index < scene.textures.length; index++) {
  89960. var texture = scene.textures[index];
  89961. if (!texture.canRescale || texture.getContext) {
  89962. continue;
  89963. }
  89964. var currentSize = texture.getSize();
  89965. var maxDimension = Math.max(currentSize.width, currentSize.height);
  89966. if (maxDimension > this.maximumSize) {
  89967. texture.scale(this.step);
  89968. allDone = false;
  89969. }
  89970. }
  89971. return allDone;
  89972. };
  89973. return TextureOptimization;
  89974. }(SceneOptimization));
  89975. BABYLON.TextureOptimization = TextureOptimization;
  89976. /**
  89977. * Defines an optimization used to increase or decrease the rendering resolution
  89978. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89979. */
  89980. var HardwareScalingOptimization = /** @class */ (function (_super) {
  89981. __extends(HardwareScalingOptimization, _super);
  89982. /**
  89983. * Creates the HardwareScalingOptimization object
  89984. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89985. * @param maximumScale defines the maximum scale to use (2 by default)
  89986. * @param step defines the step to use between two passes (0.5 by default)
  89987. */
  89988. function HardwareScalingOptimization(
  89989. /**
  89990. * Defines the priority of this optimization (0 by default which means first in the list)
  89991. */
  89992. priority,
  89993. /**
  89994. * Defines the maximum scale to use (2 by default)
  89995. */
  89996. maximumScale,
  89997. /**
  89998. * Defines the step to use between two passes (0.5 by default)
  89999. */
  90000. step) {
  90001. if (priority === void 0) { priority = 0; }
  90002. if (maximumScale === void 0) { maximumScale = 2; }
  90003. if (step === void 0) { step = 0.25; }
  90004. var _this = _super.call(this, priority) || this;
  90005. _this.priority = priority;
  90006. _this.maximumScale = maximumScale;
  90007. _this.step = step;
  90008. _this._currentScale = -1;
  90009. _this._directionOffset = 1;
  90010. return _this;
  90011. }
  90012. /**
  90013. * Gets a string describing the action executed by the current optimization
  90014. * @return description string
  90015. */
  90016. HardwareScalingOptimization.prototype.getDescription = function () {
  90017. return "Setting hardware scaling level to " + this._currentScale;
  90018. };
  90019. /**
  90020. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90021. * @param scene defines the current scene where to apply this optimization
  90022. * @param optimizer defines the current optimizer
  90023. * @returns true if everything that can be done was applied
  90024. */
  90025. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90026. if (this._currentScale === -1) {
  90027. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90028. if (this._currentScale > this.maximumScale) {
  90029. this._directionOffset = -1;
  90030. }
  90031. }
  90032. this._currentScale += this._directionOffset * this.step;
  90033. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90034. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90035. };
  90036. ;
  90037. return HardwareScalingOptimization;
  90038. }(SceneOptimization));
  90039. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90040. /**
  90041. * Defines an optimization used to remove shadows
  90042. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90043. */
  90044. var ShadowsOptimization = /** @class */ (function (_super) {
  90045. __extends(ShadowsOptimization, _super);
  90046. function ShadowsOptimization() {
  90047. return _super !== null && _super.apply(this, arguments) || this;
  90048. }
  90049. /**
  90050. * Gets a string describing the action executed by the current optimization
  90051. * @return description string
  90052. */
  90053. ShadowsOptimization.prototype.getDescription = function () {
  90054. return "Turning shadows on/off";
  90055. };
  90056. /**
  90057. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90058. * @param scene defines the current scene where to apply this optimization
  90059. * @param optimizer defines the current optimizer
  90060. * @returns true if everything that can be done was applied
  90061. */
  90062. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90063. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90064. return true;
  90065. };
  90066. ;
  90067. return ShadowsOptimization;
  90068. }(SceneOptimization));
  90069. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90070. /**
  90071. * Defines an optimization used to turn post-processes off
  90072. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90073. */
  90074. var PostProcessesOptimization = /** @class */ (function (_super) {
  90075. __extends(PostProcessesOptimization, _super);
  90076. function PostProcessesOptimization() {
  90077. return _super !== null && _super.apply(this, arguments) || this;
  90078. }
  90079. /**
  90080. * Gets a string describing the action executed by the current optimization
  90081. * @return description string
  90082. */
  90083. PostProcessesOptimization.prototype.getDescription = function () {
  90084. return "Turning post-processes on/off";
  90085. };
  90086. /**
  90087. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90088. * @param scene defines the current scene where to apply this optimization
  90089. * @param optimizer defines the current optimizer
  90090. * @returns true if everything that can be done was applied
  90091. */
  90092. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90093. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90094. return true;
  90095. };
  90096. ;
  90097. return PostProcessesOptimization;
  90098. }(SceneOptimization));
  90099. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90100. /**
  90101. * Defines an optimization used to turn lens flares off
  90102. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90103. */
  90104. var LensFlaresOptimization = /** @class */ (function (_super) {
  90105. __extends(LensFlaresOptimization, _super);
  90106. function LensFlaresOptimization() {
  90107. return _super !== null && _super.apply(this, arguments) || this;
  90108. }
  90109. /**
  90110. * Gets a string describing the action executed by the current optimization
  90111. * @return description string
  90112. */
  90113. LensFlaresOptimization.prototype.getDescription = function () {
  90114. return "Turning lens flares on/off";
  90115. };
  90116. /**
  90117. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90118. * @param scene defines the current scene where to apply this optimization
  90119. * @param optimizer defines the current optimizer
  90120. * @returns true if everything that can be done was applied
  90121. */
  90122. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90123. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90124. return true;
  90125. };
  90126. ;
  90127. return LensFlaresOptimization;
  90128. }(SceneOptimization));
  90129. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90130. /**
  90131. * Defines an optimization based on user defined callback.
  90132. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90133. */
  90134. var CustomOptimization = /** @class */ (function (_super) {
  90135. __extends(CustomOptimization, _super);
  90136. function CustomOptimization() {
  90137. return _super !== null && _super.apply(this, arguments) || this;
  90138. }
  90139. /**
  90140. * Gets a string describing the action executed by the current optimization
  90141. * @returns description string
  90142. */
  90143. CustomOptimization.prototype.getDescription = function () {
  90144. if (this.onGetDescription) {
  90145. return this.onGetDescription();
  90146. }
  90147. return "Running user defined callback";
  90148. };
  90149. /**
  90150. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90151. * @param scene defines the current scene where to apply this optimization
  90152. * @param optimizer defines the current optimizer
  90153. * @returns true if everything that can be done was applied
  90154. */
  90155. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90156. if (this.onApply) {
  90157. return this.onApply(scene, optimizer);
  90158. }
  90159. return true;
  90160. };
  90161. ;
  90162. return CustomOptimization;
  90163. }(SceneOptimization));
  90164. BABYLON.CustomOptimization = CustomOptimization;
  90165. /**
  90166. * Defines an optimization used to turn particles off
  90167. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90168. */
  90169. var ParticlesOptimization = /** @class */ (function (_super) {
  90170. __extends(ParticlesOptimization, _super);
  90171. function ParticlesOptimization() {
  90172. return _super !== null && _super.apply(this, arguments) || this;
  90173. }
  90174. /**
  90175. * Gets a string describing the action executed by the current optimization
  90176. * @return description string
  90177. */
  90178. ParticlesOptimization.prototype.getDescription = function () {
  90179. return "Turning particles on/off";
  90180. };
  90181. /**
  90182. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90183. * @param scene defines the current scene where to apply this optimization
  90184. * @param optimizer defines the current optimizer
  90185. * @returns true if everything that can be done was applied
  90186. */
  90187. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90188. scene.particlesEnabled = optimizer.isInImprovementMode;
  90189. return true;
  90190. };
  90191. ;
  90192. return ParticlesOptimization;
  90193. }(SceneOptimization));
  90194. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90195. /**
  90196. * Defines an optimization used to turn render targets off
  90197. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90198. */
  90199. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90200. __extends(RenderTargetsOptimization, _super);
  90201. function RenderTargetsOptimization() {
  90202. return _super !== null && _super.apply(this, arguments) || this;
  90203. }
  90204. /**
  90205. * Gets a string describing the action executed by the current optimization
  90206. * @return description string
  90207. */
  90208. RenderTargetsOptimization.prototype.getDescription = function () {
  90209. return "Turning render targets off";
  90210. };
  90211. /**
  90212. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90213. * @param scene defines the current scene where to apply this optimization
  90214. * @param optimizer defines the current optimizer
  90215. * @returns true if everything that can be done was applied
  90216. */
  90217. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90218. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90219. return true;
  90220. };
  90221. ;
  90222. return RenderTargetsOptimization;
  90223. }(SceneOptimization));
  90224. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90225. /**
  90226. * Defines an optimization used to merge meshes with compatible materials
  90227. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90228. */
  90229. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90230. __extends(MergeMeshesOptimization, _super);
  90231. function MergeMeshesOptimization() {
  90232. var _this = _super !== null && _super.apply(this, arguments) || this;
  90233. _this._canBeMerged = function (abstractMesh) {
  90234. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90235. return false;
  90236. }
  90237. var mesh = abstractMesh;
  90238. if (!mesh.isVisible || !mesh.isEnabled()) {
  90239. return false;
  90240. }
  90241. if (mesh.instances.length > 0) {
  90242. return false;
  90243. }
  90244. if (mesh.skeleton || mesh.hasLODLevels) {
  90245. return false;
  90246. }
  90247. if (mesh.parent) {
  90248. return false;
  90249. }
  90250. return true;
  90251. };
  90252. return _this;
  90253. }
  90254. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90255. /**
  90256. * Gets or sets a boolean which defines if optimization octree has to be updated
  90257. */
  90258. get: function () {
  90259. return MergeMeshesOptimization._UpdateSelectionTree;
  90260. },
  90261. /**
  90262. * Gets or sets a boolean which defines if optimization octree has to be updated
  90263. */
  90264. set: function (value) {
  90265. MergeMeshesOptimization._UpdateSelectionTree = value;
  90266. },
  90267. enumerable: true,
  90268. configurable: true
  90269. });
  90270. /**
  90271. * Gets a string describing the action executed by the current optimization
  90272. * @return description string
  90273. */
  90274. MergeMeshesOptimization.prototype.getDescription = function () {
  90275. return "Merging similar meshes together";
  90276. };
  90277. /**
  90278. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90279. * @param scene defines the current scene where to apply this optimization
  90280. * @param optimizer defines the current optimizer
  90281. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90282. * @returns true if everything that can be done was applied
  90283. */
  90284. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90285. var globalPool = scene.meshes.slice(0);
  90286. var globalLength = globalPool.length;
  90287. for (var index = 0; index < globalLength; index++) {
  90288. var currentPool = new Array();
  90289. var current = globalPool[index];
  90290. // Checks
  90291. if (!this._canBeMerged(current)) {
  90292. continue;
  90293. }
  90294. currentPool.push(current);
  90295. // Find compatible meshes
  90296. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90297. var otherMesh = globalPool[subIndex];
  90298. if (!this._canBeMerged(otherMesh)) {
  90299. continue;
  90300. }
  90301. if (otherMesh.material !== current.material) {
  90302. continue;
  90303. }
  90304. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90305. continue;
  90306. }
  90307. currentPool.push(otherMesh);
  90308. globalLength--;
  90309. globalPool.splice(subIndex, 1);
  90310. subIndex--;
  90311. }
  90312. if (currentPool.length < 2) {
  90313. continue;
  90314. }
  90315. // Merge meshes
  90316. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90317. }
  90318. if (updateSelectionTree != undefined) {
  90319. if (updateSelectionTree) {
  90320. scene.createOrUpdateSelectionOctree();
  90321. }
  90322. }
  90323. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90324. scene.createOrUpdateSelectionOctree();
  90325. }
  90326. return true;
  90327. };
  90328. ;
  90329. MergeMeshesOptimization._UpdateSelectionTree = false;
  90330. return MergeMeshesOptimization;
  90331. }(SceneOptimization));
  90332. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90333. /**
  90334. * Defines a list of options used by SceneOptimizer
  90335. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90336. */
  90337. var SceneOptimizerOptions = /** @class */ (function () {
  90338. /**
  90339. * Creates a new list of options used by SceneOptimizer
  90340. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90341. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90342. */
  90343. function SceneOptimizerOptions(
  90344. /**
  90345. * Defines the target frame rate to reach (60 by default)
  90346. */
  90347. targetFrameRate,
  90348. /**
  90349. * Defines the interval between two checkes (2000ms by default)
  90350. */
  90351. trackerDuration) {
  90352. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90353. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90354. this.targetFrameRate = targetFrameRate;
  90355. this.trackerDuration = trackerDuration;
  90356. /**
  90357. * Gets the list of optimizations to apply
  90358. */
  90359. this.optimizations = new Array();
  90360. }
  90361. /**
  90362. * Add a new optimization
  90363. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90364. * @returns the current SceneOptimizerOptions
  90365. */
  90366. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90367. this.optimizations.push(optimization);
  90368. return this;
  90369. };
  90370. /**
  90371. * Add a new custom optimization
  90372. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90373. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90374. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90375. * @returns the current SceneOptimizerOptions
  90376. */
  90377. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90378. if (priority === void 0) { priority = 0; }
  90379. var optimization = new CustomOptimization(priority);
  90380. optimization.onApply = onApply;
  90381. optimization.onGetDescription = onGetDescription;
  90382. this.optimizations.push(optimization);
  90383. return this;
  90384. };
  90385. /**
  90386. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90387. * @param targetFrameRate defines the target frame rate (60 by default)
  90388. * @returns a SceneOptimizerOptions object
  90389. */
  90390. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90391. var result = new SceneOptimizerOptions(targetFrameRate);
  90392. var priority = 0;
  90393. result.addOptimization(new MergeMeshesOptimization(priority));
  90394. result.addOptimization(new ShadowsOptimization(priority));
  90395. result.addOptimization(new LensFlaresOptimization(priority));
  90396. // Next priority
  90397. priority++;
  90398. result.addOptimization(new PostProcessesOptimization(priority));
  90399. result.addOptimization(new ParticlesOptimization(priority));
  90400. // Next priority
  90401. priority++;
  90402. result.addOptimization(new TextureOptimization(priority, 1024));
  90403. return result;
  90404. };
  90405. /**
  90406. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90407. * @param targetFrameRate defines the target frame rate (60 by default)
  90408. * @returns a SceneOptimizerOptions object
  90409. */
  90410. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90411. var result = new SceneOptimizerOptions(targetFrameRate);
  90412. var priority = 0;
  90413. result.addOptimization(new MergeMeshesOptimization(priority));
  90414. result.addOptimization(new ShadowsOptimization(priority));
  90415. result.addOptimization(new LensFlaresOptimization(priority));
  90416. // Next priority
  90417. priority++;
  90418. result.addOptimization(new PostProcessesOptimization(priority));
  90419. result.addOptimization(new ParticlesOptimization(priority));
  90420. // Next priority
  90421. priority++;
  90422. result.addOptimization(new TextureOptimization(priority, 512));
  90423. // Next priority
  90424. priority++;
  90425. result.addOptimization(new RenderTargetsOptimization(priority));
  90426. // Next priority
  90427. priority++;
  90428. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90429. return result;
  90430. };
  90431. /**
  90432. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90433. * @param targetFrameRate defines the target frame rate (60 by default)
  90434. * @returns a SceneOptimizerOptions object
  90435. */
  90436. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90437. var result = new SceneOptimizerOptions(targetFrameRate);
  90438. var priority = 0;
  90439. result.addOptimization(new MergeMeshesOptimization(priority));
  90440. result.addOptimization(new ShadowsOptimization(priority));
  90441. result.addOptimization(new LensFlaresOptimization(priority));
  90442. // Next priority
  90443. priority++;
  90444. result.addOptimization(new PostProcessesOptimization(priority));
  90445. result.addOptimization(new ParticlesOptimization(priority));
  90446. // Next priority
  90447. priority++;
  90448. result.addOptimization(new TextureOptimization(priority, 256));
  90449. // Next priority
  90450. priority++;
  90451. result.addOptimization(new RenderTargetsOptimization(priority));
  90452. // Next priority
  90453. priority++;
  90454. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90455. return result;
  90456. };
  90457. return SceneOptimizerOptions;
  90458. }());
  90459. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90460. /**
  90461. * Class used to run optimizations in order to reach a target frame rate
  90462. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90463. */
  90464. var SceneOptimizer = /** @class */ (function () {
  90465. /**
  90466. * Creates a new SceneOptimizer
  90467. * @param scene defines the scene to work on
  90468. * @param options defines the options to use with the SceneOptimizer
  90469. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90470. * @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)
  90471. */
  90472. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90473. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90474. if (improvementMode === void 0) { improvementMode = false; }
  90475. var _this = this;
  90476. this._isRunning = false;
  90477. this._currentPriorityLevel = 0;
  90478. this._targetFrameRate = 60;
  90479. this._trackerDuration = 2000;
  90480. this._currentFrameRate = 0;
  90481. this._improvementMode = false;
  90482. /**
  90483. * Defines an observable called when the optimizer reaches the target frame rate
  90484. */
  90485. this.onSuccessObservable = new BABYLON.Observable();
  90486. /**
  90487. * Defines an observable called when the optimizer enables an optimization
  90488. */
  90489. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90490. /**
  90491. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90492. */
  90493. this.onFailureObservable = new BABYLON.Observable();
  90494. if (!options) {
  90495. this._options = new SceneOptimizerOptions();
  90496. }
  90497. else {
  90498. this._options = options;
  90499. }
  90500. if (this._options.targetFrameRate) {
  90501. this._targetFrameRate = this._options.targetFrameRate;
  90502. }
  90503. if (this._options.trackerDuration) {
  90504. this._trackerDuration = this._options.trackerDuration;
  90505. }
  90506. if (autoGeneratePriorities) {
  90507. var priority = 0;
  90508. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90509. var optim = _a[_i];
  90510. optim.priority = priority++;
  90511. }
  90512. }
  90513. this._improvementMode = improvementMode;
  90514. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90515. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90516. _this._sceneDisposeObserver = null;
  90517. _this.dispose();
  90518. });
  90519. }
  90520. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90521. /**
  90522. * Gets a boolean indicating if the optimizer is in improvement mode
  90523. */
  90524. get: function () {
  90525. return this._improvementMode;
  90526. },
  90527. enumerable: true,
  90528. configurable: true
  90529. });
  90530. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90531. /**
  90532. * Gets the current priority level (0 at start)
  90533. */
  90534. get: function () {
  90535. return this._currentPriorityLevel;
  90536. },
  90537. enumerable: true,
  90538. configurable: true
  90539. });
  90540. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90541. /**
  90542. * Gets the current frame rate checked by the SceneOptimizer
  90543. */
  90544. get: function () {
  90545. return this._currentFrameRate;
  90546. },
  90547. enumerable: true,
  90548. configurable: true
  90549. });
  90550. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90551. /**
  90552. * Gets or sets the current target frame rate (60 by default)
  90553. */
  90554. get: function () {
  90555. return this._targetFrameRate;
  90556. },
  90557. /**
  90558. * Gets or sets the current target frame rate (60 by default)
  90559. */
  90560. set: function (value) {
  90561. this._targetFrameRate = value;
  90562. },
  90563. enumerable: true,
  90564. configurable: true
  90565. });
  90566. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90567. /**
  90568. * Gets or sets the current interval between two checks (every 2000ms by default)
  90569. */
  90570. get: function () {
  90571. return this._trackerDuration;
  90572. },
  90573. /**
  90574. * Gets or sets the current interval between two checks (every 2000ms by default)
  90575. */
  90576. set: function (value) {
  90577. this._trackerDuration = value;
  90578. },
  90579. enumerable: true,
  90580. configurable: true
  90581. });
  90582. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90583. /**
  90584. * Gets the list of active optimizations
  90585. */
  90586. get: function () {
  90587. return this._options.optimizations;
  90588. },
  90589. enumerable: true,
  90590. configurable: true
  90591. });
  90592. /**
  90593. * Stops the current optimizer
  90594. */
  90595. SceneOptimizer.prototype.stop = function () {
  90596. this._isRunning = false;
  90597. };
  90598. /**
  90599. * Reset the optimizer to initial step (current priority level = 0)
  90600. */
  90601. SceneOptimizer.prototype.reset = function () {
  90602. this._currentPriorityLevel = 0;
  90603. };
  90604. /**
  90605. * Start the optimizer. By default it will try to reach a specific framerate
  90606. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90607. */
  90608. SceneOptimizer.prototype.start = function () {
  90609. var _this = this;
  90610. if (this._isRunning) {
  90611. return;
  90612. }
  90613. this._isRunning = true;
  90614. // Let's wait for the scene to be ready before running our check
  90615. this._scene.executeWhenReady(function () {
  90616. setTimeout(function () {
  90617. _this._checkCurrentState();
  90618. }, _this._trackerDuration);
  90619. });
  90620. };
  90621. SceneOptimizer.prototype._checkCurrentState = function () {
  90622. var _this = this;
  90623. if (!this._isRunning) {
  90624. return;
  90625. }
  90626. var scene = this._scene;
  90627. var options = this._options;
  90628. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90629. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90630. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90631. this._isRunning = false;
  90632. this.onSuccessObservable.notifyObservers(this);
  90633. return;
  90634. }
  90635. // Apply current level of optimizations
  90636. var allDone = true;
  90637. var noOptimizationApplied = true;
  90638. for (var index = 0; index < options.optimizations.length; index++) {
  90639. var optimization = options.optimizations[index];
  90640. if (optimization.priority === this._currentPriorityLevel) {
  90641. noOptimizationApplied = false;
  90642. allDone = allDone && optimization.apply(scene, this);
  90643. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90644. }
  90645. }
  90646. // If no optimization was applied, this is a failure :(
  90647. if (noOptimizationApplied) {
  90648. this._isRunning = false;
  90649. this.onFailureObservable.notifyObservers(this);
  90650. return;
  90651. }
  90652. // If all optimizations were done, move to next level
  90653. if (allDone) {
  90654. this._currentPriorityLevel++;
  90655. }
  90656. // Let's the system running for a specific amount of time before checking FPS
  90657. scene.executeWhenReady(function () {
  90658. setTimeout(function () {
  90659. _this._checkCurrentState();
  90660. }, _this._trackerDuration);
  90661. });
  90662. };
  90663. /**
  90664. * Release all resources
  90665. */
  90666. SceneOptimizer.prototype.dispose = function () {
  90667. this.stop();
  90668. this.onSuccessObservable.clear();
  90669. this.onFailureObservable.clear();
  90670. this.onNewOptimizationAppliedObservable.clear();
  90671. if (this._sceneDisposeObserver) {
  90672. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90673. }
  90674. };
  90675. /**
  90676. * Helper function to create a SceneOptimizer with one single line of code
  90677. * @param scene defines the scene to work on
  90678. * @param options defines the options to use with the SceneOptimizer
  90679. * @param onSuccess defines a callback to call on success
  90680. * @param onFailure defines a callback to call on failure
  90681. * @returns the new SceneOptimizer object
  90682. */
  90683. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90684. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90685. if (onSuccess) {
  90686. optimizer.onSuccessObservable.add(function () {
  90687. onSuccess();
  90688. });
  90689. }
  90690. if (onFailure) {
  90691. optimizer.onFailureObservable.add(function () {
  90692. onFailure();
  90693. });
  90694. }
  90695. optimizer.start();
  90696. return optimizer;
  90697. };
  90698. return SceneOptimizer;
  90699. }());
  90700. BABYLON.SceneOptimizer = SceneOptimizer;
  90701. })(BABYLON || (BABYLON = {}));
  90702. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90703. var BABYLON;
  90704. (function (BABYLON) {
  90705. var OutlineRenderer = /** @class */ (function () {
  90706. function OutlineRenderer(scene) {
  90707. this.zOffset = 1;
  90708. this._scene = scene;
  90709. }
  90710. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90711. var _this = this;
  90712. if (useOverlay === void 0) { useOverlay = false; }
  90713. var scene = this._scene;
  90714. var engine = this._scene.getEngine();
  90715. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90716. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90717. return;
  90718. }
  90719. var mesh = subMesh.getRenderingMesh();
  90720. var material = subMesh.getMaterial();
  90721. if (!material || !scene.activeCamera) {
  90722. return;
  90723. }
  90724. engine.enableEffect(this._effect);
  90725. // Logarithmic depth
  90726. if (material.useLogarithmicDepth) {
  90727. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90728. }
  90729. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90730. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90731. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90732. // Bones
  90733. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90734. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90735. }
  90736. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90737. // Alpha test
  90738. if (material && material.needAlphaTesting()) {
  90739. var alphaTexture = material.getAlphaTestTexture();
  90740. if (alphaTexture) {
  90741. this._effect.setTexture("diffuseSampler", alphaTexture);
  90742. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90743. }
  90744. }
  90745. engine.setZOffset(-this.zOffset);
  90746. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90747. engine.setZOffset(0);
  90748. };
  90749. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90750. var defines = [];
  90751. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90752. var mesh = subMesh.getMesh();
  90753. var material = subMesh.getMaterial();
  90754. if (material) {
  90755. // Alpha test
  90756. if (material.needAlphaTesting()) {
  90757. defines.push("#define ALPHATEST");
  90758. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90759. attribs.push(BABYLON.VertexBuffer.UVKind);
  90760. defines.push("#define UV1");
  90761. }
  90762. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90763. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90764. defines.push("#define UV2");
  90765. }
  90766. }
  90767. //Logarithmic depth
  90768. if (material.useLogarithmicDepth) {
  90769. defines.push("#define LOGARITHMICDEPTH");
  90770. }
  90771. }
  90772. // Bones
  90773. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90774. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90775. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90776. if (mesh.numBoneInfluencers > 4) {
  90777. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90778. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90779. }
  90780. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90781. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90782. }
  90783. else {
  90784. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90785. }
  90786. // Instances
  90787. if (useInstances) {
  90788. defines.push("#define INSTANCES");
  90789. attribs.push("world0");
  90790. attribs.push("world1");
  90791. attribs.push("world2");
  90792. attribs.push("world3");
  90793. }
  90794. // Get correct effect
  90795. var join = defines.join("\n");
  90796. if (this._cachedDefines !== join) {
  90797. this._cachedDefines = join;
  90798. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90799. }
  90800. return this._effect.isReady();
  90801. };
  90802. return OutlineRenderer;
  90803. }());
  90804. BABYLON.OutlineRenderer = OutlineRenderer;
  90805. })(BABYLON || (BABYLON = {}));
  90806. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90807. var BABYLON;
  90808. (function (BABYLON) {
  90809. var FaceAdjacencies = /** @class */ (function () {
  90810. function FaceAdjacencies() {
  90811. this.edges = new Array();
  90812. this.edgesConnectedCount = 0;
  90813. }
  90814. return FaceAdjacencies;
  90815. }());
  90816. var EdgesRenderer = /** @class */ (function () {
  90817. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90818. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90819. if (epsilon === void 0) { epsilon = 0.95; }
  90820. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90821. this.edgesWidthScalerForOrthographic = 1000.0;
  90822. this.edgesWidthScalerForPerspective = 50.0;
  90823. this._linesPositions = new Array();
  90824. this._linesNormals = new Array();
  90825. this._linesIndices = new Array();
  90826. this._buffers = {};
  90827. this._checkVerticesInsteadOfIndices = false;
  90828. this._source = source;
  90829. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90830. this._epsilon = epsilon;
  90831. this._prepareRessources();
  90832. this._generateEdgesLines();
  90833. }
  90834. EdgesRenderer.prototype._prepareRessources = function () {
  90835. if (this._lineShader) {
  90836. return;
  90837. }
  90838. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90839. attributes: ["position", "normal"],
  90840. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90841. });
  90842. this._lineShader.disableDepthWrite = true;
  90843. this._lineShader.backFaceCulling = false;
  90844. };
  90845. EdgesRenderer.prototype._rebuild = function () {
  90846. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90847. if (buffer) {
  90848. buffer._rebuild();
  90849. }
  90850. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90851. if (buffer) {
  90852. buffer._rebuild();
  90853. }
  90854. var scene = this._source.getScene();
  90855. var engine = scene.getEngine();
  90856. this._ib = engine.createIndexBuffer(this._linesIndices);
  90857. };
  90858. EdgesRenderer.prototype.dispose = function () {
  90859. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90860. if (buffer) {
  90861. buffer.dispose();
  90862. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90863. }
  90864. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90865. if (buffer) {
  90866. buffer.dispose();
  90867. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90868. }
  90869. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90870. this._lineShader.dispose();
  90871. };
  90872. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90873. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90874. return 0;
  90875. }
  90876. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90877. return 1;
  90878. }
  90879. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90880. return 2;
  90881. }
  90882. return -1;
  90883. };
  90884. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90885. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90886. return 0;
  90887. }
  90888. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90889. return 1;
  90890. }
  90891. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90892. return 2;
  90893. }
  90894. return -1;
  90895. };
  90896. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90897. var needToCreateLine;
  90898. if (edge === undefined) {
  90899. needToCreateLine = true;
  90900. }
  90901. else {
  90902. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  90903. needToCreateLine = dotProduct < this._epsilon;
  90904. }
  90905. if (needToCreateLine) {
  90906. var offset = this._linesPositions.length / 3;
  90907. var normal = p0.subtract(p1);
  90908. normal.normalize();
  90909. // Positions
  90910. this._linesPositions.push(p0.x);
  90911. this._linesPositions.push(p0.y);
  90912. this._linesPositions.push(p0.z);
  90913. this._linesPositions.push(p0.x);
  90914. this._linesPositions.push(p0.y);
  90915. this._linesPositions.push(p0.z);
  90916. this._linesPositions.push(p1.x);
  90917. this._linesPositions.push(p1.y);
  90918. this._linesPositions.push(p1.z);
  90919. this._linesPositions.push(p1.x);
  90920. this._linesPositions.push(p1.y);
  90921. this._linesPositions.push(p1.z);
  90922. // Normals
  90923. this._linesNormals.push(p1.x);
  90924. this._linesNormals.push(p1.y);
  90925. this._linesNormals.push(p1.z);
  90926. this._linesNormals.push(-1);
  90927. this._linesNormals.push(p1.x);
  90928. this._linesNormals.push(p1.y);
  90929. this._linesNormals.push(p1.z);
  90930. this._linesNormals.push(1);
  90931. this._linesNormals.push(p0.x);
  90932. this._linesNormals.push(p0.y);
  90933. this._linesNormals.push(p0.z);
  90934. this._linesNormals.push(-1);
  90935. this._linesNormals.push(p0.x);
  90936. this._linesNormals.push(p0.y);
  90937. this._linesNormals.push(p0.z);
  90938. this._linesNormals.push(1);
  90939. // Indices
  90940. this._linesIndices.push(offset);
  90941. this._linesIndices.push(offset + 1);
  90942. this._linesIndices.push(offset + 2);
  90943. this._linesIndices.push(offset);
  90944. this._linesIndices.push(offset + 2);
  90945. this._linesIndices.push(offset + 3);
  90946. }
  90947. };
  90948. EdgesRenderer.prototype._generateEdgesLines = function () {
  90949. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90950. var indices = this._source.getIndices();
  90951. if (!indices || !positions) {
  90952. return;
  90953. }
  90954. // First let's find adjacencies
  90955. var adjacencies = new Array();
  90956. var faceNormals = new Array();
  90957. var index;
  90958. var faceAdjacencies;
  90959. // Prepare faces
  90960. for (index = 0; index < indices.length; index += 3) {
  90961. faceAdjacencies = new FaceAdjacencies();
  90962. var p0Index = indices[index];
  90963. var p1Index = indices[index + 1];
  90964. var p2Index = indices[index + 2];
  90965. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  90966. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  90967. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  90968. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  90969. faceNormal.normalize();
  90970. faceNormals.push(faceNormal);
  90971. adjacencies.push(faceAdjacencies);
  90972. }
  90973. // Scan
  90974. for (index = 0; index < adjacencies.length; index++) {
  90975. faceAdjacencies = adjacencies[index];
  90976. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  90977. var otherFaceAdjacencies = adjacencies[otherIndex];
  90978. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  90979. break;
  90980. }
  90981. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  90982. continue;
  90983. }
  90984. var otherP0 = indices[otherIndex * 3];
  90985. var otherP1 = indices[otherIndex * 3 + 1];
  90986. var otherP2 = indices[otherIndex * 3 + 2];
  90987. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  90988. var otherEdgeIndex = 0;
  90989. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  90990. continue;
  90991. }
  90992. switch (edgeIndex) {
  90993. case 0:
  90994. if (this._checkVerticesInsteadOfIndices) {
  90995. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90996. }
  90997. else {
  90998. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  90999. }
  91000. break;
  91001. case 1:
  91002. if (this._checkVerticesInsteadOfIndices) {
  91003. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91004. }
  91005. else {
  91006. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91007. }
  91008. break;
  91009. case 2:
  91010. if (this._checkVerticesInsteadOfIndices) {
  91011. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91012. }
  91013. else {
  91014. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91015. }
  91016. break;
  91017. }
  91018. if (otherEdgeIndex === -1) {
  91019. continue;
  91020. }
  91021. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91022. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91023. faceAdjacencies.edgesConnectedCount++;
  91024. otherFaceAdjacencies.edgesConnectedCount++;
  91025. if (faceAdjacencies.edgesConnectedCount === 3) {
  91026. break;
  91027. }
  91028. }
  91029. }
  91030. }
  91031. // Create lines
  91032. for (index = 0; index < adjacencies.length; index++) {
  91033. // 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
  91034. var current = adjacencies[index];
  91035. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91036. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91037. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91038. }
  91039. // Merge into a single mesh
  91040. var engine = this._source.getScene().getEngine();
  91041. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91042. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91043. this._ib = engine.createIndexBuffer(this._linesIndices);
  91044. this._indicesCount = this._linesIndices.length;
  91045. };
  91046. EdgesRenderer.prototype.render = function () {
  91047. var scene = this._source.getScene();
  91048. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91049. return;
  91050. }
  91051. var engine = scene.getEngine();
  91052. this._lineShader._preBind();
  91053. // VBOs
  91054. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91055. scene.resetCachedMaterial();
  91056. this._lineShader.setColor4("color", this._source.edgesColor);
  91057. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91058. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91059. }
  91060. else {
  91061. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91062. }
  91063. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91064. this._lineShader.bind(this._source.getWorldMatrix());
  91065. // Draw order
  91066. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91067. this._lineShader.unbind();
  91068. engine.setDepthWrite(true);
  91069. };
  91070. return EdgesRenderer;
  91071. }());
  91072. BABYLON.EdgesRenderer = EdgesRenderer;
  91073. })(BABYLON || (BABYLON = {}));
  91074. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91075. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91076. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91077. s = arguments[i];
  91078. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91079. t[p] = s[p];
  91080. }
  91081. return t;
  91082. };
  91083. var BABYLON;
  91084. (function (BABYLON) {
  91085. /**
  91086. * The effect layer Helps adding post process effect blended with the main pass.
  91087. *
  91088. * This can be for instance use to generate glow or higlight effects on the scene.
  91089. *
  91090. * The effect layer class can not be used directly and is intented to inherited from to be
  91091. * customized per effects.
  91092. */
  91093. var EffectLayer = /** @class */ (function () {
  91094. /**
  91095. * Instantiates a new effect Layer and references it in the scene.
  91096. * @param name The name of the layer
  91097. * @param scene The scene to use the layer in
  91098. */
  91099. function EffectLayer(
  91100. /** The Friendly of the effect in the scene */
  91101. name, scene) {
  91102. this._vertexBuffers = {};
  91103. this._maxSize = 0;
  91104. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91105. this._shouldRender = true;
  91106. this._postProcesses = [];
  91107. this._textures = [];
  91108. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91109. /**
  91110. * The clear color of the texture used to generate the glow map.
  91111. */
  91112. this.neutralColor = new BABYLON.Color4();
  91113. /**
  91114. * Specifies wether the highlight layer is enabled or not.
  91115. */
  91116. this.isEnabled = true;
  91117. /**
  91118. * An event triggered when the effect layer has been disposed.
  91119. */
  91120. this.onDisposeObservable = new BABYLON.Observable();
  91121. /**
  91122. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91123. */
  91124. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91125. /**
  91126. * An event triggered when the generated texture is being merged in the scene.
  91127. */
  91128. this.onBeforeComposeObservable = new BABYLON.Observable();
  91129. /**
  91130. * An event triggered when the generated texture has been merged in the scene.
  91131. */
  91132. this.onAfterComposeObservable = new BABYLON.Observable();
  91133. /**
  91134. * An event triggered when the efffect layer changes its size.
  91135. */
  91136. this.onSizeChangedObservable = new BABYLON.Observable();
  91137. this.name = name;
  91138. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91139. this._engine = scene.getEngine();
  91140. this._maxSize = this._engine.getCaps().maxTextureSize;
  91141. this._scene.effectLayers.push(this);
  91142. // Generate Buffers
  91143. this._generateIndexBuffer();
  91144. this._genrateVertexBuffer();
  91145. }
  91146. Object.defineProperty(EffectLayer.prototype, "camera", {
  91147. /**
  91148. * Gets the camera attached to the layer.
  91149. */
  91150. get: function () {
  91151. return this._effectLayerOptions.camera;
  91152. },
  91153. enumerable: true,
  91154. configurable: true
  91155. });
  91156. /**
  91157. * Initializes the effect layer with the required options.
  91158. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91159. */
  91160. EffectLayer.prototype._init = function (options) {
  91161. // Adapt options
  91162. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91163. this._setMainTextureSize();
  91164. this._createMainTexture();
  91165. this._createTextureAndPostProcesses();
  91166. this._mergeEffect = this._createMergeEffect();
  91167. };
  91168. /**
  91169. * Generates the index buffer of the full screen quad blending to the main canvas.
  91170. */
  91171. EffectLayer.prototype._generateIndexBuffer = function () {
  91172. // Indices
  91173. var indices = [];
  91174. indices.push(0);
  91175. indices.push(1);
  91176. indices.push(2);
  91177. indices.push(0);
  91178. indices.push(2);
  91179. indices.push(3);
  91180. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91181. };
  91182. /**
  91183. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91184. */
  91185. EffectLayer.prototype._genrateVertexBuffer = function () {
  91186. // VBO
  91187. var vertices = [];
  91188. vertices.push(1, 1);
  91189. vertices.push(-1, 1);
  91190. vertices.push(-1, -1);
  91191. vertices.push(1, -1);
  91192. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91193. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91194. };
  91195. /**
  91196. * Sets the main texture desired size which is the closest power of two
  91197. * of the engine canvas size.
  91198. */
  91199. EffectLayer.prototype._setMainTextureSize = function () {
  91200. if (this._effectLayerOptions.mainTextureFixedSize) {
  91201. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91202. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91203. }
  91204. else {
  91205. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91206. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91207. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91208. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91209. }
  91210. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91211. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91212. };
  91213. /**
  91214. * Creates the main texture for the effect layer.
  91215. */
  91216. EffectLayer.prototype._createMainTexture = function () {
  91217. var _this = this;
  91218. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91219. width: this._mainTextureDesiredSize.width,
  91220. height: this._mainTextureDesiredSize.height
  91221. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91222. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91223. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91224. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91225. this._mainTexture.anisotropicFilteringLevel = 1;
  91226. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91227. this._mainTexture.renderParticles = false;
  91228. this._mainTexture.renderList = null;
  91229. this._mainTexture.ignoreCameraViewport = true;
  91230. // Custom render function
  91231. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91232. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91233. var index;
  91234. var engine = _this._scene.getEngine();
  91235. if (depthOnlySubMeshes.length) {
  91236. engine.setColorWrite(false);
  91237. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91238. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91239. }
  91240. engine.setColorWrite(true);
  91241. }
  91242. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91243. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91244. }
  91245. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91246. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91247. }
  91248. for (index = 0; index < transparentSubMeshes.length; index++) {
  91249. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91250. }
  91251. };
  91252. this._mainTexture.onClearObservable.add(function (engine) {
  91253. engine.clear(_this.neutralColor, true, true, true);
  91254. });
  91255. };
  91256. /**
  91257. * Checks for the readiness of the element composing the layer.
  91258. * @param subMesh the mesh to check for
  91259. * @param useInstances specify wether or not to use instances to render the mesh
  91260. * @param emissiveTexture the associated emissive texture used to generate the glow
  91261. * @return true if ready otherwise, false
  91262. */
  91263. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91264. var material = subMesh.getMaterial();
  91265. if (!material) {
  91266. return false;
  91267. }
  91268. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91269. return false;
  91270. }
  91271. var defines = [];
  91272. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91273. var mesh = subMesh.getMesh();
  91274. var uv1 = false;
  91275. var uv2 = false;
  91276. // Alpha test
  91277. if (material && material.needAlphaTesting()) {
  91278. var alphaTexture = material.getAlphaTestTexture();
  91279. if (alphaTexture) {
  91280. defines.push("#define ALPHATEST");
  91281. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91282. alphaTexture.coordinatesIndex === 1) {
  91283. defines.push("#define DIFFUSEUV2");
  91284. uv2 = true;
  91285. }
  91286. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91287. defines.push("#define DIFFUSEUV1");
  91288. uv1 = true;
  91289. }
  91290. }
  91291. }
  91292. // Emissive
  91293. if (emissiveTexture) {
  91294. defines.push("#define EMISSIVE");
  91295. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91296. emissiveTexture.coordinatesIndex === 1) {
  91297. defines.push("#define EMISSIVEUV2");
  91298. uv2 = true;
  91299. }
  91300. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91301. defines.push("#define EMISSIVEUV1");
  91302. uv1 = true;
  91303. }
  91304. }
  91305. if (uv1) {
  91306. attribs.push(BABYLON.VertexBuffer.UVKind);
  91307. defines.push("#define UV1");
  91308. }
  91309. if (uv2) {
  91310. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91311. defines.push("#define UV2");
  91312. }
  91313. // Bones
  91314. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91315. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91316. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91317. if (mesh.numBoneInfluencers > 4) {
  91318. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91319. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91320. }
  91321. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91322. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91323. }
  91324. else {
  91325. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91326. }
  91327. // Morph targets
  91328. var manager = mesh.morphTargetManager;
  91329. var morphInfluencers = 0;
  91330. if (manager) {
  91331. if (manager.numInfluencers > 0) {
  91332. defines.push("#define MORPHTARGETS");
  91333. morphInfluencers = manager.numInfluencers;
  91334. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91335. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91336. }
  91337. }
  91338. // Instances
  91339. if (useInstances) {
  91340. defines.push("#define INSTANCES");
  91341. attribs.push("world0");
  91342. attribs.push("world1");
  91343. attribs.push("world2");
  91344. attribs.push("world3");
  91345. }
  91346. // Get correct effect
  91347. var join = defines.join("\n");
  91348. if (this._cachedDefines !== join) {
  91349. this._cachedDefines = join;
  91350. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91351. }
  91352. return this._effectLayerMapGenerationEffect.isReady();
  91353. };
  91354. /**
  91355. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91356. */
  91357. EffectLayer.prototype.render = function () {
  91358. var currentEffect = this._mergeEffect;
  91359. // Check
  91360. if (!currentEffect.isReady())
  91361. return;
  91362. for (var i = 0; i < this._postProcesses.length; i++) {
  91363. if (!this._postProcesses[i].isReady()) {
  91364. return;
  91365. }
  91366. }
  91367. var engine = this._scene.getEngine();
  91368. this.onBeforeComposeObservable.notifyObservers(this);
  91369. // Render
  91370. engine.enableEffect(currentEffect);
  91371. engine.setState(false);
  91372. // VBOs
  91373. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91374. // Cache
  91375. var previousAlphaMode = engine.getAlphaMode();
  91376. // Go Blend.
  91377. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91378. // Blends the map on the main canvas.
  91379. this._internalRender(currentEffect);
  91380. // Restore Alpha
  91381. engine.setAlphaMode(previousAlphaMode);
  91382. this.onAfterComposeObservable.notifyObservers(this);
  91383. // Handle size changes.
  91384. var size = this._mainTexture.getSize();
  91385. this._setMainTextureSize();
  91386. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91387. // Recreate RTT and post processes on size change.
  91388. this.onSizeChangedObservable.notifyObservers(this);
  91389. this._disposeTextureAndPostProcesses();
  91390. this._createMainTexture();
  91391. this._createTextureAndPostProcesses();
  91392. }
  91393. };
  91394. /**
  91395. * Determine if a given mesh will be used in the current effect.
  91396. * @param mesh mesh to test
  91397. * @returns true if the mesh will be used
  91398. */
  91399. EffectLayer.prototype.hasMesh = function (mesh) {
  91400. return true;
  91401. };
  91402. /**
  91403. * Returns true if the layer contains information to display, otherwise false.
  91404. * @returns true if the glow layer should be rendered
  91405. */
  91406. EffectLayer.prototype.shouldRender = function () {
  91407. return this.isEnabled && this._shouldRender;
  91408. };
  91409. /**
  91410. * Returns true if the mesh should render, otherwise false.
  91411. * @param mesh The mesh to render
  91412. * @returns true if it should render otherwise false
  91413. */
  91414. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91415. return true;
  91416. };
  91417. /**
  91418. * Returns true if the mesh should render, otherwise false.
  91419. * @param mesh The mesh to render
  91420. * @returns true if it should render otherwise false
  91421. */
  91422. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91423. return true;
  91424. };
  91425. /**
  91426. * Renders the submesh passed in parameter to the generation map.
  91427. */
  91428. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91429. var _this = this;
  91430. if (!this.shouldRender()) {
  91431. return;
  91432. }
  91433. var material = subMesh.getMaterial();
  91434. var mesh = subMesh.getRenderingMesh();
  91435. var scene = this._scene;
  91436. var engine = scene.getEngine();
  91437. if (!material) {
  91438. return;
  91439. }
  91440. // Do not block in blend mode.
  91441. if (material.needAlphaBlendingForMesh(mesh)) {
  91442. return;
  91443. }
  91444. // Culling
  91445. engine.setState(material.backFaceCulling);
  91446. // Managing instances
  91447. var batch = mesh._getInstancesRenderList(subMesh._id);
  91448. if (batch.mustReturn) {
  91449. return;
  91450. }
  91451. // Early Exit per mesh
  91452. if (!this._shouldRenderMesh(mesh)) {
  91453. return;
  91454. }
  91455. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91456. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91457. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91458. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91459. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91460. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91461. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91462. // Alpha test
  91463. if (material && material.needAlphaTesting()) {
  91464. var alphaTexture = material.getAlphaTestTexture();
  91465. if (alphaTexture) {
  91466. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91467. var textureMatrix = alphaTexture.getTextureMatrix();
  91468. if (textureMatrix) {
  91469. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91470. }
  91471. }
  91472. }
  91473. // Glow emissive only
  91474. if (this._emissiveTextureAndColor.texture) {
  91475. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91476. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91477. }
  91478. // Bones
  91479. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91480. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91481. }
  91482. // Morph targets
  91483. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91484. // Draw
  91485. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91486. }
  91487. else {
  91488. // Need to reset refresh rate of the shadowMap
  91489. this._mainTexture.resetRefreshCounter();
  91490. }
  91491. };
  91492. /**
  91493. * Rebuild the required buffers.
  91494. * @hidden Internal use only.
  91495. */
  91496. EffectLayer.prototype._rebuild = function () {
  91497. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91498. if (vb) {
  91499. vb._rebuild();
  91500. }
  91501. this._generateIndexBuffer();
  91502. };
  91503. /**
  91504. * Dispose only the render target textures and post process.
  91505. */
  91506. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91507. this._mainTexture.dispose();
  91508. for (var i = 0; i < this._postProcesses.length; i++) {
  91509. if (this._postProcesses[i]) {
  91510. this._postProcesses[i].dispose();
  91511. }
  91512. }
  91513. this._postProcesses = [];
  91514. for (var i = 0; i < this._textures.length; i++) {
  91515. if (this._textures[i]) {
  91516. this._textures[i].dispose();
  91517. }
  91518. }
  91519. this._textures = [];
  91520. };
  91521. /**
  91522. * Dispose the highlight layer and free resources.
  91523. */
  91524. EffectLayer.prototype.dispose = function () {
  91525. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91526. if (vertexBuffer) {
  91527. vertexBuffer.dispose();
  91528. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91529. }
  91530. if (this._indexBuffer) {
  91531. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91532. this._indexBuffer = null;
  91533. }
  91534. // Clean textures and post processes
  91535. this._disposeTextureAndPostProcesses();
  91536. // Remove from scene
  91537. var index = this._scene.effectLayers.indexOf(this, 0);
  91538. if (index > -1) {
  91539. this._scene.effectLayers.splice(index, 1);
  91540. }
  91541. // Callback
  91542. this.onDisposeObservable.notifyObservers(this);
  91543. this.onDisposeObservable.clear();
  91544. this.onBeforeRenderMainTextureObservable.clear();
  91545. this.onBeforeComposeObservable.clear();
  91546. this.onAfterComposeObservable.clear();
  91547. this.onSizeChangedObservable.clear();
  91548. };
  91549. /**
  91550. * Gets the class name of the effect layer
  91551. * @returns the string with the class name of the effect layer
  91552. */
  91553. EffectLayer.prototype.getClassName = function () {
  91554. return "EffectLayer";
  91555. };
  91556. /**
  91557. * Creates an effect layer from parsed effect layer data
  91558. * @param parsedEffectLayer defines effect layer data
  91559. * @param scene defines the current scene
  91560. * @param rootUrl defines the root URL containing the effect layer information
  91561. * @returns a parsed effect Layer
  91562. */
  91563. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91564. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91565. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91566. };
  91567. __decorate([
  91568. BABYLON.serialize()
  91569. ], EffectLayer.prototype, "name", void 0);
  91570. __decorate([
  91571. BABYLON.serializeAsColor4()
  91572. ], EffectLayer.prototype, "neutralColor", void 0);
  91573. __decorate([
  91574. BABYLON.serialize()
  91575. ], EffectLayer.prototype, "isEnabled", void 0);
  91576. __decorate([
  91577. BABYLON.serializeAsCameraReference()
  91578. ], EffectLayer.prototype, "camera", null);
  91579. return EffectLayer;
  91580. }());
  91581. BABYLON.EffectLayer = EffectLayer;
  91582. })(BABYLON || (BABYLON = {}));
  91583. //# sourceMappingURL=babylon.effectLayer.js.map
  91584. var BABYLON;
  91585. (function (BABYLON) {
  91586. /**
  91587. * Special Glow Blur post process only blurring the alpha channel
  91588. * It enforces keeping the most luminous color in the color channel.
  91589. */
  91590. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91591. __extends(GlowBlurPostProcess, _super);
  91592. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91593. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91594. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91595. _this.direction = direction;
  91596. _this.kernel = kernel;
  91597. _this.onApplyObservable.add(function (effect) {
  91598. effect.setFloat2("screenSize", _this.width, _this.height);
  91599. effect.setVector2("direction", _this.direction);
  91600. effect.setFloat("blurWidth", _this.kernel);
  91601. });
  91602. return _this;
  91603. }
  91604. return GlowBlurPostProcess;
  91605. }(BABYLON.PostProcess));
  91606. /**
  91607. * The highlight layer Helps adding a glow effect around a mesh.
  91608. *
  91609. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91610. * glowy meshes to your scene.
  91611. *
  91612. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91613. */
  91614. var HighlightLayer = /** @class */ (function (_super) {
  91615. __extends(HighlightLayer, _super);
  91616. /**
  91617. * Instantiates a new highlight Layer and references it to the scene..
  91618. * @param name The name of the layer
  91619. * @param scene The scene to use the layer in
  91620. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91621. */
  91622. function HighlightLayer(name, scene, options) {
  91623. var _this = _super.call(this, name, scene) || this;
  91624. _this.name = name;
  91625. /**
  91626. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91627. */
  91628. _this.innerGlow = true;
  91629. /**
  91630. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91631. */
  91632. _this.outerGlow = true;
  91633. /**
  91634. * An event triggered when the highlight layer is being blurred.
  91635. */
  91636. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91637. /**
  91638. * An event triggered when the highlight layer has been blurred.
  91639. */
  91640. _this.onAfterBlurObservable = new BABYLON.Observable();
  91641. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91642. _this._meshes = {};
  91643. _this._excludedMeshes = {};
  91644. _this.neutralColor = HighlightLayer.NeutralColor;
  91645. // Warn on stencil
  91646. if (!_this._engine.isStencilEnable) {
  91647. 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 }");
  91648. }
  91649. // Adapt options
  91650. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91651. // Initialize the layer
  91652. _this._init({
  91653. alphaBlendingMode: _this._options.alphaBlendingMode,
  91654. camera: _this._options.camera,
  91655. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91656. mainTextureRatio: _this._options.mainTextureRatio
  91657. });
  91658. // Do not render as long as no meshes have been added
  91659. _this._shouldRender = false;
  91660. return _this;
  91661. }
  91662. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91663. /**
  91664. * Gets the horizontal size of the blur.
  91665. */
  91666. get: function () {
  91667. return this._horizontalBlurPostprocess.kernel;
  91668. },
  91669. /**
  91670. * Specifies the horizontal size of the blur.
  91671. */
  91672. set: function (value) {
  91673. this._horizontalBlurPostprocess.kernel = value;
  91674. },
  91675. enumerable: true,
  91676. configurable: true
  91677. });
  91678. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91679. /**
  91680. * Gets the vertical size of the blur.
  91681. */
  91682. get: function () {
  91683. return this._verticalBlurPostprocess.kernel;
  91684. },
  91685. /**
  91686. * Specifies the vertical size of the blur.
  91687. */
  91688. set: function (value) {
  91689. this._verticalBlurPostprocess.kernel = value;
  91690. },
  91691. enumerable: true,
  91692. configurable: true
  91693. });
  91694. /**
  91695. * Get the effect name of the layer.
  91696. * @return The effect name
  91697. */
  91698. HighlightLayer.prototype.getEffectName = function () {
  91699. return HighlightLayer.EffectName;
  91700. };
  91701. /**
  91702. * Create the merge effect. This is the shader use to blit the information back
  91703. * to the main canvas at the end of the scene rendering.
  91704. */
  91705. HighlightLayer.prototype._createMergeEffect = function () {
  91706. // Effect
  91707. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91708. };
  91709. /**
  91710. * Creates the render target textures and post processes used in the highlight layer.
  91711. */
  91712. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91713. var _this = this;
  91714. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91715. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91716. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91717. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91718. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91719. width: blurTextureWidth,
  91720. height: blurTextureHeight
  91721. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91722. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91723. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91724. this._blurTexture.anisotropicFilteringLevel = 16;
  91725. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91726. this._blurTexture.renderParticles = false;
  91727. this._blurTexture.ignoreCameraViewport = true;
  91728. this._textures = [this._blurTexture];
  91729. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91730. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91731. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91732. effect.setTexture("textureSampler", _this._mainTexture);
  91733. });
  91734. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91735. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91736. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91737. });
  91738. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91739. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91740. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91741. });
  91742. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91743. }
  91744. else {
  91745. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91746. width: blurTextureWidth,
  91747. height: blurTextureHeight
  91748. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91749. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91750. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91751. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91752. effect.setTexture("textureSampler", _this._mainTexture);
  91753. });
  91754. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91755. width: blurTextureWidth,
  91756. height: blurTextureHeight
  91757. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91758. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91759. }
  91760. this._mainTexture.onAfterUnbindObservable.add(function () {
  91761. _this.onBeforeBlurObservable.notifyObservers(_this);
  91762. var internalTexture = _this._blurTexture.getInternalTexture();
  91763. if (internalTexture) {
  91764. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91765. }
  91766. _this.onAfterBlurObservable.notifyObservers(_this);
  91767. });
  91768. // Prevent autoClear.
  91769. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91770. };
  91771. /**
  91772. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91773. */
  91774. HighlightLayer.prototype.needStencil = function () {
  91775. return true;
  91776. };
  91777. /**
  91778. * Checks for the readiness of the element composing the layer.
  91779. * @param subMesh the mesh to check for
  91780. * @param useInstances specify wether or not to use instances to render the mesh
  91781. * @param emissiveTexture the associated emissive texture used to generate the glow
  91782. * @return true if ready otherwise, false
  91783. */
  91784. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91785. var material = subMesh.getMaterial();
  91786. var mesh = subMesh.getRenderingMesh();
  91787. if (!material || !mesh || !this._meshes) {
  91788. return false;
  91789. }
  91790. var emissiveTexture = null;
  91791. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91792. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91793. emissiveTexture = material.emissiveTexture;
  91794. }
  91795. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91796. };
  91797. /**
  91798. * Implementation specific of rendering the generating effect on the main canvas.
  91799. * @param effect The effect used to render through
  91800. */
  91801. HighlightLayer.prototype._internalRender = function (effect) {
  91802. // Texture
  91803. effect.setTexture("textureSampler", this._blurTexture);
  91804. // Cache
  91805. var engine = this._engine;
  91806. var previousStencilBuffer = engine.getStencilBuffer();
  91807. var previousStencilFunction = engine.getStencilFunction();
  91808. var previousStencilMask = engine.getStencilMask();
  91809. var previousStencilOperationPass = engine.getStencilOperationPass();
  91810. var previousStencilOperationFail = engine.getStencilOperationFail();
  91811. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91812. var previousStencilReference = engine.getStencilFunctionReference();
  91813. // Stencil operations
  91814. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91815. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91816. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91817. // Draw order
  91818. engine.setStencilMask(0x00);
  91819. engine.setStencilBuffer(true);
  91820. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91821. // 2 passes inner outer
  91822. if (this.outerGlow) {
  91823. effect.setFloat("offset", 0);
  91824. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91825. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91826. }
  91827. if (this.innerGlow) {
  91828. effect.setFloat("offset", 1);
  91829. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91830. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91831. }
  91832. // Restore Cache
  91833. engine.setStencilFunction(previousStencilFunction);
  91834. engine.setStencilMask(previousStencilMask);
  91835. engine.setStencilBuffer(previousStencilBuffer);
  91836. engine.setStencilOperationPass(previousStencilOperationPass);
  91837. engine.setStencilOperationFail(previousStencilOperationFail);
  91838. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91839. engine.setStencilFunctionReference(previousStencilReference);
  91840. };
  91841. /**
  91842. * Returns true if the layer contains information to display, otherwise false.
  91843. */
  91844. HighlightLayer.prototype.shouldRender = function () {
  91845. if (_super.prototype.shouldRender.call(this)) {
  91846. return this._meshes ? true : false;
  91847. }
  91848. return false;
  91849. };
  91850. /**
  91851. * Returns true if the mesh should render, otherwise false.
  91852. * @param mesh The mesh to render
  91853. * @returns true if it should render otherwise false
  91854. */
  91855. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91856. // Excluded Mesh
  91857. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91858. return false;
  91859. }
  91860. ;
  91861. return true;
  91862. };
  91863. /**
  91864. * Sets the required values for both the emissive texture and and the main color.
  91865. */
  91866. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91867. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91868. if (highlightLayerMesh) {
  91869. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91870. }
  91871. else {
  91872. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91873. }
  91874. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91875. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91876. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91877. }
  91878. else {
  91879. this._emissiveTextureAndColor.texture = null;
  91880. }
  91881. };
  91882. /**
  91883. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91884. * @param mesh The mesh to exclude from the highlight layer
  91885. */
  91886. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91887. if (!this._excludedMeshes) {
  91888. return;
  91889. }
  91890. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91891. if (!meshExcluded) {
  91892. this._excludedMeshes[mesh.uniqueId] = {
  91893. mesh: mesh,
  91894. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91895. mesh.getEngine().setStencilBuffer(false);
  91896. }),
  91897. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91898. mesh.getEngine().setStencilBuffer(true);
  91899. }),
  91900. };
  91901. }
  91902. };
  91903. /**
  91904. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  91905. * @param mesh The mesh to highlight
  91906. */
  91907. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  91908. if (!this._excludedMeshes) {
  91909. return;
  91910. }
  91911. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91912. if (meshExcluded) {
  91913. if (meshExcluded.beforeRender) {
  91914. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  91915. }
  91916. if (meshExcluded.afterRender) {
  91917. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  91918. }
  91919. }
  91920. this._excludedMeshes[mesh.uniqueId] = null;
  91921. };
  91922. /**
  91923. * Determine if a given mesh will be highlighted by the current HighlightLayer
  91924. * @param mesh mesh to test
  91925. * @returns true if the mesh will be highlighted by the current HighlightLayer
  91926. */
  91927. HighlightLayer.prototype.hasMesh = function (mesh) {
  91928. if (!this._meshes) {
  91929. return false;
  91930. }
  91931. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  91932. };
  91933. /**
  91934. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  91935. * @param mesh The mesh to highlight
  91936. * @param color The color of the highlight
  91937. * @param glowEmissiveOnly Extract the glow from the emissive texture
  91938. */
  91939. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  91940. var _this = this;
  91941. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  91942. if (!this._meshes) {
  91943. return;
  91944. }
  91945. var meshHighlight = this._meshes[mesh.uniqueId];
  91946. if (meshHighlight) {
  91947. meshHighlight.color = color;
  91948. }
  91949. else {
  91950. this._meshes[mesh.uniqueId] = {
  91951. mesh: mesh,
  91952. color: color,
  91953. // Lambda required for capture due to Observable this context
  91954. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  91955. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  91956. _this._defaultStencilReference(mesh);
  91957. }
  91958. else {
  91959. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  91960. }
  91961. }),
  91962. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  91963. glowEmissiveOnly: glowEmissiveOnly
  91964. };
  91965. }
  91966. this._shouldRender = true;
  91967. };
  91968. /**
  91969. * Remove a mesh from the highlight layer in order to make it stop glowing.
  91970. * @param mesh The mesh to highlight
  91971. */
  91972. HighlightLayer.prototype.removeMesh = function (mesh) {
  91973. if (!this._meshes) {
  91974. return;
  91975. }
  91976. var meshHighlight = this._meshes[mesh.uniqueId];
  91977. if (meshHighlight) {
  91978. if (meshHighlight.observerHighlight) {
  91979. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91980. }
  91981. if (meshHighlight.observerDefault) {
  91982. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91983. }
  91984. delete this._meshes[mesh.uniqueId];
  91985. }
  91986. this._shouldRender = false;
  91987. for (var meshHighlightToCheck in this._meshes) {
  91988. if (this._meshes[meshHighlightToCheck]) {
  91989. this._shouldRender = true;
  91990. break;
  91991. }
  91992. }
  91993. };
  91994. /**
  91995. * Force the stencil to the normal expected value for none glowing parts
  91996. */
  91997. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  91998. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  91999. };
  92000. /**
  92001. * Free any resources and references associated to a mesh.
  92002. * Internal use
  92003. * @param mesh The mesh to free.
  92004. */
  92005. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92006. this.removeMesh(mesh);
  92007. this.removeExcludedMesh(mesh);
  92008. };
  92009. /**
  92010. * Dispose the highlight layer and free resources.
  92011. */
  92012. HighlightLayer.prototype.dispose = function () {
  92013. if (this._meshes) {
  92014. // Clean mesh references
  92015. for (var id in this._meshes) {
  92016. var meshHighlight = this._meshes[id];
  92017. if (meshHighlight && meshHighlight.mesh) {
  92018. if (meshHighlight.observerHighlight) {
  92019. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92020. }
  92021. if (meshHighlight.observerDefault) {
  92022. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92023. }
  92024. }
  92025. }
  92026. this._meshes = null;
  92027. }
  92028. if (this._excludedMeshes) {
  92029. for (var id in this._excludedMeshes) {
  92030. var meshHighlight = this._excludedMeshes[id];
  92031. if (meshHighlight) {
  92032. if (meshHighlight.beforeRender) {
  92033. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92034. }
  92035. if (meshHighlight.afterRender) {
  92036. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92037. }
  92038. }
  92039. }
  92040. this._excludedMeshes = null;
  92041. }
  92042. _super.prototype.dispose.call(this);
  92043. };
  92044. /**
  92045. * Gets the class name of the effect layer
  92046. * @returns the string with the class name of the effect layer
  92047. */
  92048. HighlightLayer.prototype.getClassName = function () {
  92049. return "HighlightLayer";
  92050. };
  92051. /**
  92052. * Serializes this Highlight layer
  92053. * @returns a serialized Highlight layer object
  92054. */
  92055. HighlightLayer.prototype.serialize = function () {
  92056. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92057. serializationObject.customType = "BABYLON.HighlightLayer";
  92058. // Highlighted meshes
  92059. serializationObject.meshes = [];
  92060. if (this._meshes) {
  92061. for (var m in this._meshes) {
  92062. var mesh = this._meshes[m];
  92063. if (mesh) {
  92064. serializationObject.meshes.push({
  92065. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92066. color: mesh.color.asArray(),
  92067. meshId: mesh.mesh.id
  92068. });
  92069. }
  92070. }
  92071. }
  92072. // Excluded meshes
  92073. serializationObject.excludedMeshes = [];
  92074. if (this._excludedMeshes) {
  92075. for (var e in this._excludedMeshes) {
  92076. var excludedMesh = this._excludedMeshes[e];
  92077. if (excludedMesh) {
  92078. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92079. }
  92080. }
  92081. }
  92082. return serializationObject;
  92083. };
  92084. /**
  92085. * Creates a Highlight layer from parsed Highlight layer data
  92086. * @param parsedHightlightLayer defines the Highlight layer data
  92087. * @param scene defines the current scene
  92088. * @param rootUrl defines the root URL containing the Highlight layer information
  92089. * @returns a parsed Highlight layer
  92090. */
  92091. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92092. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92093. var index;
  92094. // Excluded meshes
  92095. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92096. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92097. if (mesh) {
  92098. hl.addExcludedMesh(mesh);
  92099. }
  92100. }
  92101. // Included meshes
  92102. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92103. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92104. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92105. if (mesh) {
  92106. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92107. }
  92108. }
  92109. return hl;
  92110. };
  92111. /**
  92112. * Effect Name of the highlight layer.
  92113. */
  92114. HighlightLayer.EffectName = "HighlightLayer";
  92115. /**
  92116. * The neutral color used during the preparation of the glow effect.
  92117. * This is black by default as the blend operation is a blend operation.
  92118. */
  92119. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92120. /**
  92121. * Stencil value used for glowing meshes.
  92122. */
  92123. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92124. /**
  92125. * Stencil value used for the other meshes in the scene.
  92126. */
  92127. HighlightLayer.NormalMeshStencilReference = 0x01;
  92128. __decorate([
  92129. BABYLON.serialize()
  92130. ], HighlightLayer.prototype, "innerGlow", void 0);
  92131. __decorate([
  92132. BABYLON.serialize()
  92133. ], HighlightLayer.prototype, "outerGlow", void 0);
  92134. __decorate([
  92135. BABYLON.serialize()
  92136. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92137. __decorate([
  92138. BABYLON.serialize()
  92139. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92140. __decorate([
  92141. BABYLON.serialize("options")
  92142. ], HighlightLayer.prototype, "_options", void 0);
  92143. return HighlightLayer;
  92144. }(BABYLON.EffectLayer));
  92145. BABYLON.HighlightLayer = HighlightLayer;
  92146. })(BABYLON || (BABYLON = {}));
  92147. //# sourceMappingURL=babylon.highlightLayer.js.map
  92148. var BABYLON;
  92149. (function (BABYLON) {
  92150. /**
  92151. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92152. *
  92153. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92154. * glowy meshes to your scene.
  92155. *
  92156. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92157. */
  92158. var GlowLayer = /** @class */ (function (_super) {
  92159. __extends(GlowLayer, _super);
  92160. /**
  92161. * Instantiates a new glow Layer and references it to the scene.
  92162. * @param name The name of the layer
  92163. * @param scene The scene to use the layer in
  92164. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92165. */
  92166. function GlowLayer(name, scene, options) {
  92167. var _this = _super.call(this, name, scene) || this;
  92168. _this._intensity = 1.0;
  92169. _this._includedOnlyMeshes = [];
  92170. _this._excludedMeshes = [];
  92171. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92172. // Adapt options
  92173. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92174. // Initialize the layer
  92175. _this._init({
  92176. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92177. camera: _this._options.camera,
  92178. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92179. mainTextureRatio: _this._options.mainTextureRatio
  92180. });
  92181. return _this;
  92182. }
  92183. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92184. /**
  92185. * Gets the kernel size of the blur.
  92186. */
  92187. get: function () {
  92188. return this._horizontalBlurPostprocess1.kernel;
  92189. },
  92190. /**
  92191. * Sets the kernel size of the blur.
  92192. */
  92193. set: function (value) {
  92194. this._horizontalBlurPostprocess1.kernel = value;
  92195. this._verticalBlurPostprocess1.kernel = value;
  92196. this._horizontalBlurPostprocess2.kernel = value;
  92197. this._verticalBlurPostprocess2.kernel = value;
  92198. },
  92199. enumerable: true,
  92200. configurable: true
  92201. });
  92202. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92203. /**
  92204. * Gets the glow intensity.
  92205. */
  92206. get: function () {
  92207. return this._intensity;
  92208. },
  92209. /**
  92210. * Sets the glow intensity.
  92211. */
  92212. set: function (value) {
  92213. this._intensity = value;
  92214. },
  92215. enumerable: true,
  92216. configurable: true
  92217. });
  92218. /**
  92219. * Get the effect name of the layer.
  92220. * @return The effect name
  92221. */
  92222. GlowLayer.prototype.getEffectName = function () {
  92223. return GlowLayer.EffectName;
  92224. };
  92225. /**
  92226. * Create the merge effect. This is the shader use to blit the information back
  92227. * to the main canvas at the end of the scene rendering.
  92228. */
  92229. GlowLayer.prototype._createMergeEffect = function () {
  92230. // Effect
  92231. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92232. };
  92233. /**
  92234. * Creates the render target textures and post processes used in the glow layer.
  92235. */
  92236. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92237. var _this = this;
  92238. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92239. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92240. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92241. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92242. var textureType = 0;
  92243. if (this._engine.getCaps().textureHalfFloatRender) {
  92244. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92245. }
  92246. else {
  92247. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92248. }
  92249. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92250. width: blurTextureWidth,
  92251. height: blurTextureHeight
  92252. }, this._scene, false, true, textureType);
  92253. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92254. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92255. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92256. this._blurTexture1.renderParticles = false;
  92257. this._blurTexture1.ignoreCameraViewport = true;
  92258. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92259. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92260. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92261. width: blurTextureWidth2,
  92262. height: blurTextureHeight2
  92263. }, this._scene, false, true, textureType);
  92264. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92265. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92266. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92267. this._blurTexture2.renderParticles = false;
  92268. this._blurTexture2.ignoreCameraViewport = true;
  92269. this._textures = [this._blurTexture1, this._blurTexture2];
  92270. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92271. width: blurTextureWidth,
  92272. height: blurTextureHeight
  92273. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92274. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92275. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92276. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92277. effect.setTexture("textureSampler", _this._mainTexture);
  92278. });
  92279. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92280. width: blurTextureWidth,
  92281. height: blurTextureHeight
  92282. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92283. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92284. width: blurTextureWidth2,
  92285. height: blurTextureHeight2
  92286. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92287. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92288. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92289. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92290. effect.setTexture("textureSampler", _this._blurTexture1);
  92291. });
  92292. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92293. width: blurTextureWidth2,
  92294. height: blurTextureHeight2
  92295. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92296. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92297. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92298. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92299. this._mainTexture.samples = this._options.mainTextureSamples;
  92300. this._mainTexture.onAfterUnbindObservable.add(function () {
  92301. var internalTexture = _this._blurTexture1.getInternalTexture();
  92302. if (internalTexture) {
  92303. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92304. internalTexture = _this._blurTexture2.getInternalTexture();
  92305. if (internalTexture) {
  92306. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92307. }
  92308. }
  92309. });
  92310. // Prevent autoClear.
  92311. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92312. };
  92313. /**
  92314. * Checks for the readiness of the element composing the layer.
  92315. * @param subMesh the mesh to check for
  92316. * @param useInstances specify wether or not to use instances to render the mesh
  92317. * @param emissiveTexture the associated emissive texture used to generate the glow
  92318. * @return true if ready otherwise, false
  92319. */
  92320. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92321. var material = subMesh.getMaterial();
  92322. var mesh = subMesh.getRenderingMesh();
  92323. if (!material || !mesh) {
  92324. return false;
  92325. }
  92326. var emissiveTexture = material.emissiveTexture;
  92327. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92328. };
  92329. /**
  92330. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92331. */
  92332. GlowLayer.prototype.needStencil = function () {
  92333. return false;
  92334. };
  92335. /**
  92336. * Implementation specific of rendering the generating effect on the main canvas.
  92337. * @param effect The effect used to render through
  92338. */
  92339. GlowLayer.prototype._internalRender = function (effect) {
  92340. // Texture
  92341. effect.setTexture("textureSampler", this._blurTexture1);
  92342. effect.setTexture("textureSampler2", this._blurTexture2);
  92343. effect.setFloat("offset", this._intensity);
  92344. // Cache
  92345. var engine = this._engine;
  92346. var previousStencilBuffer = engine.getStencilBuffer();
  92347. // Draw order
  92348. engine.setStencilBuffer(false);
  92349. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92350. // Draw order
  92351. engine.setStencilBuffer(previousStencilBuffer);
  92352. };
  92353. /**
  92354. * Sets the required values for both the emissive texture and and the main color.
  92355. */
  92356. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92357. var textureLevel = 1.0;
  92358. if (this.customEmissiveTextureSelector) {
  92359. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92360. }
  92361. else {
  92362. if (material) {
  92363. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92364. if (this._emissiveTextureAndColor.texture) {
  92365. textureLevel = this._emissiveTextureAndColor.texture.level;
  92366. }
  92367. }
  92368. else {
  92369. this._emissiveTextureAndColor.texture = null;
  92370. }
  92371. }
  92372. if (this.customEmissiveColorSelector) {
  92373. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92374. }
  92375. else {
  92376. if (material.emissiveColor) {
  92377. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92378. }
  92379. else {
  92380. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92381. }
  92382. }
  92383. };
  92384. /**
  92385. * Returns true if the mesh should render, otherwise false.
  92386. * @param mesh The mesh to render
  92387. * @returns true if it should render otherwise false
  92388. */
  92389. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92390. return this.hasMesh(mesh);
  92391. };
  92392. /**
  92393. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92394. * @param mesh The mesh to exclude from the glow layer
  92395. */
  92396. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92397. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92398. this._excludedMeshes.push(mesh.uniqueId);
  92399. }
  92400. };
  92401. /**
  92402. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92403. * @param mesh The mesh to remove
  92404. */
  92405. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92406. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92407. if (index !== -1) {
  92408. this._excludedMeshes.splice(index, 1);
  92409. }
  92410. };
  92411. /**
  92412. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92413. * @param mesh The mesh to include in the glow layer
  92414. */
  92415. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92416. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92417. this._includedOnlyMeshes.push(mesh.uniqueId);
  92418. }
  92419. };
  92420. /**
  92421. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92422. * @param mesh The mesh to remove
  92423. */
  92424. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92425. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92426. if (index !== -1) {
  92427. this._includedOnlyMeshes.splice(index, 1);
  92428. }
  92429. };
  92430. /**
  92431. * Determine if a given mesh will be used in the glow layer
  92432. * @param mesh The mesh to test
  92433. * @returns true if the mesh will be highlighted by the current glow layer
  92434. */
  92435. GlowLayer.prototype.hasMesh = function (mesh) {
  92436. // Included Mesh
  92437. if (this._includedOnlyMeshes.length) {
  92438. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92439. }
  92440. ;
  92441. // Excluded Mesh
  92442. if (this._excludedMeshes.length) {
  92443. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92444. }
  92445. ;
  92446. return true;
  92447. };
  92448. /**
  92449. * Free any resources and references associated to a mesh.
  92450. * Internal use
  92451. * @param mesh The mesh to free.
  92452. */
  92453. GlowLayer.prototype._disposeMesh = function (mesh) {
  92454. this.removeIncludedOnlyMesh(mesh);
  92455. this.removeExcludedMesh(mesh);
  92456. };
  92457. /**
  92458. * Gets the class name of the effect layer
  92459. * @returns the string with the class name of the effect layer
  92460. */
  92461. GlowLayer.prototype.getClassName = function () {
  92462. return "GlowLayer";
  92463. };
  92464. /**
  92465. * Serializes this glow layer
  92466. * @returns a serialized glow layer object
  92467. */
  92468. GlowLayer.prototype.serialize = function () {
  92469. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92470. serializationObject.customType = "BABYLON.GlowLayer";
  92471. var index;
  92472. // Included meshes
  92473. serializationObject.includedMeshes = [];
  92474. if (this._includedOnlyMeshes.length) {
  92475. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92476. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92477. if (mesh) {
  92478. serializationObject.includedMeshes.push(mesh.id);
  92479. }
  92480. }
  92481. }
  92482. // Excluded meshes
  92483. serializationObject.excludedMeshes = [];
  92484. if (this._excludedMeshes.length) {
  92485. for (index = 0; index < this._excludedMeshes.length; index++) {
  92486. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92487. if (mesh) {
  92488. serializationObject.excludedMeshes.push(mesh.id);
  92489. }
  92490. }
  92491. }
  92492. return serializationObject;
  92493. };
  92494. /**
  92495. * Creates a Glow Layer from parsed glow layer data
  92496. * @param parsedGlowLayer defines glow layer data
  92497. * @param scene defines the current scene
  92498. * @param rootUrl defines the root URL containing the glow layer information
  92499. * @returns a parsed Glow Layer
  92500. */
  92501. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92502. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92503. var index;
  92504. // Excluded meshes
  92505. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92506. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92507. if (mesh) {
  92508. gl.addExcludedMesh(mesh);
  92509. }
  92510. }
  92511. // Included meshes
  92512. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92513. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92514. if (mesh) {
  92515. gl.addIncludedOnlyMesh(mesh);
  92516. }
  92517. }
  92518. return gl;
  92519. };
  92520. /**
  92521. * Effect Name of the layer.
  92522. */
  92523. GlowLayer.EffectName = "GlowLayer";
  92524. /**
  92525. * The default blur kernel size used for the glow.
  92526. */
  92527. GlowLayer.DefaultBlurKernelSize = 32;
  92528. /**
  92529. * The default texture size ratio used for the glow.
  92530. */
  92531. GlowLayer.DefaultTextureRatio = 0.5;
  92532. __decorate([
  92533. BABYLON.serialize()
  92534. ], GlowLayer.prototype, "blurKernelSize", null);
  92535. __decorate([
  92536. BABYLON.serialize()
  92537. ], GlowLayer.prototype, "intensity", null);
  92538. __decorate([
  92539. BABYLON.serialize("options")
  92540. ], GlowLayer.prototype, "_options", void 0);
  92541. return GlowLayer;
  92542. }(BABYLON.EffectLayer));
  92543. BABYLON.GlowLayer = GlowLayer;
  92544. })(BABYLON || (BABYLON = {}));
  92545. //# sourceMappingURL=babylon.glowLayer.js.map
  92546. var BABYLON;
  92547. (function (BABYLON) {
  92548. /**
  92549. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92550. */
  92551. var AssetTaskState;
  92552. (function (AssetTaskState) {
  92553. /**
  92554. * Initialization
  92555. */
  92556. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92557. /**
  92558. * Running
  92559. */
  92560. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92561. /**
  92562. * Done
  92563. */
  92564. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92565. /**
  92566. * Error
  92567. */
  92568. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92569. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92570. /**
  92571. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92572. */
  92573. var AbstractAssetTask = /** @class */ (function () {
  92574. /**
  92575. * Creates a new {BABYLON.AssetsManager}
  92576. * @param name defines the name of the task
  92577. */
  92578. function AbstractAssetTask(
  92579. /**
  92580. * Task name
  92581. */ name) {
  92582. this.name = name;
  92583. this._isCompleted = false;
  92584. this._taskState = AssetTaskState.INIT;
  92585. }
  92586. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92587. /**
  92588. * Get if the task is completed
  92589. */
  92590. get: function () {
  92591. return this._isCompleted;
  92592. },
  92593. enumerable: true,
  92594. configurable: true
  92595. });
  92596. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92597. /**
  92598. * Gets the current state of the task
  92599. */
  92600. get: function () {
  92601. return this._taskState;
  92602. },
  92603. enumerable: true,
  92604. configurable: true
  92605. });
  92606. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92607. /**
  92608. * Gets the current error object (if task is in error)
  92609. */
  92610. get: function () {
  92611. return this._errorObject;
  92612. },
  92613. enumerable: true,
  92614. configurable: true
  92615. });
  92616. /**
  92617. * Internal only
  92618. * @hidden
  92619. */
  92620. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92621. if (this._errorObject) {
  92622. return;
  92623. }
  92624. this._errorObject = {
  92625. message: message,
  92626. exception: exception
  92627. };
  92628. };
  92629. /**
  92630. * Execute the current task
  92631. * @param scene defines the scene where you want your assets to be loaded
  92632. * @param onSuccess is a callback called when the task is successfully executed
  92633. * @param onError is a callback called if an error occurs
  92634. */
  92635. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92636. var _this = this;
  92637. this._taskState = AssetTaskState.RUNNING;
  92638. this.runTask(scene, function () {
  92639. _this.onDoneCallback(onSuccess, onError);
  92640. }, function (msg, exception) {
  92641. _this.onErrorCallback(onError, msg, exception);
  92642. });
  92643. };
  92644. /**
  92645. * Execute the current task
  92646. * @param scene defines the scene where you want your assets to be loaded
  92647. * @param onSuccess is a callback called when the task is successfully executed
  92648. * @param onError is a callback called if an error occurs
  92649. */
  92650. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92651. throw new Error("runTask is not implemented");
  92652. };
  92653. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92654. this._taskState = AssetTaskState.ERROR;
  92655. this._errorObject = {
  92656. message: message,
  92657. exception: exception
  92658. };
  92659. if (this.onError) {
  92660. this.onError(this, message, exception);
  92661. }
  92662. onError();
  92663. };
  92664. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92665. try {
  92666. this._taskState = AssetTaskState.DONE;
  92667. this._isCompleted = true;
  92668. if (this.onSuccess) {
  92669. this.onSuccess(this);
  92670. }
  92671. onSuccess();
  92672. }
  92673. catch (e) {
  92674. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92675. }
  92676. };
  92677. return AbstractAssetTask;
  92678. }());
  92679. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92680. /**
  92681. * Class used to share progress information about assets loading
  92682. */
  92683. var AssetsProgressEvent = /** @class */ (function () {
  92684. /**
  92685. * Creates a {BABYLON.AssetsProgressEvent}
  92686. * @param remainingCount defines the number of remaining tasks to process
  92687. * @param totalCount defines the total number of tasks
  92688. * @param task defines the task that was just processed
  92689. */
  92690. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92691. this.remainingCount = remainingCount;
  92692. this.totalCount = totalCount;
  92693. this.task = task;
  92694. }
  92695. return AssetsProgressEvent;
  92696. }());
  92697. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92698. /**
  92699. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92700. */
  92701. var MeshAssetTask = /** @class */ (function (_super) {
  92702. __extends(MeshAssetTask, _super);
  92703. /**
  92704. * Creates a new {BABYLON.MeshAssetTask}
  92705. * @param name defines the name of the task
  92706. * @param meshesNames defines the list of mesh's names you want to load
  92707. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92708. * @param sceneFilename defines the filename of the scene to load from
  92709. */
  92710. function MeshAssetTask(
  92711. /**
  92712. * Defines the name of the task
  92713. */
  92714. name,
  92715. /**
  92716. * Defines the list of mesh's names you want to load
  92717. */
  92718. meshesNames,
  92719. /**
  92720. * Defines the root url to use as a base to load your meshes and associated resources
  92721. */
  92722. rootUrl,
  92723. /**
  92724. * Defines the filename of the scene to load from
  92725. */
  92726. sceneFilename) {
  92727. var _this = _super.call(this, name) || this;
  92728. _this.name = name;
  92729. _this.meshesNames = meshesNames;
  92730. _this.rootUrl = rootUrl;
  92731. _this.sceneFilename = sceneFilename;
  92732. return _this;
  92733. }
  92734. /**
  92735. * Execute the current task
  92736. * @param scene defines the scene where you want your assets to be loaded
  92737. * @param onSuccess is a callback called when the task is successfully executed
  92738. * @param onError is a callback called if an error occurs
  92739. */
  92740. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92741. var _this = this;
  92742. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92743. _this.loadedMeshes = meshes;
  92744. _this.loadedParticleSystems = particleSystems;
  92745. _this.loadedSkeletons = skeletons;
  92746. onSuccess();
  92747. }, null, function (scene, message, exception) {
  92748. onError(message, exception);
  92749. });
  92750. };
  92751. return MeshAssetTask;
  92752. }(AbstractAssetTask));
  92753. BABYLON.MeshAssetTask = MeshAssetTask;
  92754. /**
  92755. * Define a task used by {BABYLON.AssetsManager} to load text content
  92756. */
  92757. var TextFileAssetTask = /** @class */ (function (_super) {
  92758. __extends(TextFileAssetTask, _super);
  92759. /**
  92760. * Creates a new TextFileAssetTask object
  92761. * @param name defines the name of the task
  92762. * @param url defines the location of the file to load
  92763. */
  92764. function TextFileAssetTask(
  92765. /**
  92766. * Defines the name of the task
  92767. */
  92768. name,
  92769. /**
  92770. * Defines the location of the file to load
  92771. */
  92772. url) {
  92773. var _this = _super.call(this, name) || this;
  92774. _this.name = name;
  92775. _this.url = url;
  92776. return _this;
  92777. }
  92778. /**
  92779. * Execute the current task
  92780. * @param scene defines the scene where you want your assets to be loaded
  92781. * @param onSuccess is a callback called when the task is successfully executed
  92782. * @param onError is a callback called if an error occurs
  92783. */
  92784. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92785. var _this = this;
  92786. scene._loadFile(this.url, function (data) {
  92787. _this.text = data;
  92788. onSuccess();
  92789. }, undefined, false, false, function (request, exception) {
  92790. if (request) {
  92791. onError(request.status + " " + request.statusText, exception);
  92792. }
  92793. });
  92794. };
  92795. return TextFileAssetTask;
  92796. }(AbstractAssetTask));
  92797. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92798. /**
  92799. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92800. */
  92801. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92802. __extends(BinaryFileAssetTask, _super);
  92803. /**
  92804. * Creates a new BinaryFileAssetTask object
  92805. * @param name defines the name of the new task
  92806. * @param url defines the location of the file to load
  92807. */
  92808. function BinaryFileAssetTask(
  92809. /**
  92810. * Defines the name of the task
  92811. */
  92812. name,
  92813. /**
  92814. * Defines the location of the file to load
  92815. */
  92816. url) {
  92817. var _this = _super.call(this, name) || this;
  92818. _this.name = name;
  92819. _this.url = url;
  92820. return _this;
  92821. }
  92822. /**
  92823. * Execute the current task
  92824. * @param scene defines the scene where you want your assets to be loaded
  92825. * @param onSuccess is a callback called when the task is successfully executed
  92826. * @param onError is a callback called if an error occurs
  92827. */
  92828. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92829. var _this = this;
  92830. scene._loadFile(this.url, function (data) {
  92831. _this.data = data;
  92832. onSuccess();
  92833. }, undefined, true, true, function (request, exception) {
  92834. if (request) {
  92835. onError(request.status + " " + request.statusText, exception);
  92836. }
  92837. });
  92838. };
  92839. return BinaryFileAssetTask;
  92840. }(AbstractAssetTask));
  92841. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92842. /**
  92843. * Define a task used by {BABYLON.AssetsManager} to load images
  92844. */
  92845. var ImageAssetTask = /** @class */ (function (_super) {
  92846. __extends(ImageAssetTask, _super);
  92847. /**
  92848. * Creates a new ImageAssetTask
  92849. * @param name defines the name of the task
  92850. * @param url defines the location of the image to load
  92851. */
  92852. function ImageAssetTask(
  92853. /**
  92854. * Defines the name of the task
  92855. */
  92856. name,
  92857. /**
  92858. * Defines the location of the image to load
  92859. */
  92860. url) {
  92861. var _this = _super.call(this, name) || this;
  92862. _this.name = name;
  92863. _this.url = url;
  92864. return _this;
  92865. }
  92866. /**
  92867. * Execute the current task
  92868. * @param scene defines the scene where you want your assets to be loaded
  92869. * @param onSuccess is a callback called when the task is successfully executed
  92870. * @param onError is a callback called if an error occurs
  92871. */
  92872. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92873. var _this = this;
  92874. var img = new Image();
  92875. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92876. img.onload = function () {
  92877. _this.image = img;
  92878. onSuccess();
  92879. };
  92880. img.onerror = function (err) {
  92881. onError("Error loading image", err);
  92882. };
  92883. img.src = this.url;
  92884. };
  92885. return ImageAssetTask;
  92886. }(AbstractAssetTask));
  92887. BABYLON.ImageAssetTask = ImageAssetTask;
  92888. /**
  92889. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92890. */
  92891. var TextureAssetTask = /** @class */ (function (_super) {
  92892. __extends(TextureAssetTask, _super);
  92893. /**
  92894. * Creates a new TextureAssetTask object
  92895. * @param name defines the name of the task
  92896. * @param url defines the location of the file to load
  92897. * @param noMipmap defines if mipmap should not be generated (default is false)
  92898. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92899. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92900. */
  92901. function TextureAssetTask(
  92902. /**
  92903. * Defines the name of the task
  92904. */
  92905. name,
  92906. /**
  92907. * Defines the location of the file to load
  92908. */
  92909. url,
  92910. /**
  92911. * Defines if mipmap should not be generated (default is false)
  92912. */
  92913. noMipmap,
  92914. /**
  92915. * Defines if texture must be inverted on Y axis (default is false)
  92916. */
  92917. invertY,
  92918. /**
  92919. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92920. */
  92921. samplingMode) {
  92922. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92923. var _this = _super.call(this, name) || this;
  92924. _this.name = name;
  92925. _this.url = url;
  92926. _this.noMipmap = noMipmap;
  92927. _this.invertY = invertY;
  92928. _this.samplingMode = samplingMode;
  92929. return _this;
  92930. }
  92931. /**
  92932. * Execute the current task
  92933. * @param scene defines the scene where you want your assets to be loaded
  92934. * @param onSuccess is a callback called when the task is successfully executed
  92935. * @param onError is a callback called if an error occurs
  92936. */
  92937. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92938. var onload = function () {
  92939. onSuccess();
  92940. };
  92941. var onerror = function (message, exception) {
  92942. onError(message, exception);
  92943. };
  92944. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  92945. };
  92946. return TextureAssetTask;
  92947. }(AbstractAssetTask));
  92948. BABYLON.TextureAssetTask = TextureAssetTask;
  92949. /**
  92950. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  92951. */
  92952. var CubeTextureAssetTask = /** @class */ (function (_super) {
  92953. __extends(CubeTextureAssetTask, _super);
  92954. /**
  92955. * Creates a new CubeTextureAssetTask
  92956. * @param name defines the name of the task
  92957. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92958. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92959. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92960. * @param files defines the explicit list of files (undefined by default)
  92961. */
  92962. function CubeTextureAssetTask(
  92963. /**
  92964. * Defines the name of the task
  92965. */
  92966. name,
  92967. /**
  92968. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92969. */
  92970. url,
  92971. /**
  92972. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92973. */
  92974. extensions,
  92975. /**
  92976. * Defines if mipmaps should not be generated (default is false)
  92977. */
  92978. noMipmap,
  92979. /**
  92980. * Defines the explicit list of files (undefined by default)
  92981. */
  92982. files) {
  92983. var _this = _super.call(this, name) || this;
  92984. _this.name = name;
  92985. _this.url = url;
  92986. _this.extensions = extensions;
  92987. _this.noMipmap = noMipmap;
  92988. _this.files = files;
  92989. return _this;
  92990. }
  92991. /**
  92992. * Execute the current task
  92993. * @param scene defines the scene where you want your assets to be loaded
  92994. * @param onSuccess is a callback called when the task is successfully executed
  92995. * @param onError is a callback called if an error occurs
  92996. */
  92997. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92998. var onload = function () {
  92999. onSuccess();
  93000. };
  93001. var onerror = function (message, exception) {
  93002. onError(message, exception);
  93003. };
  93004. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93005. };
  93006. return CubeTextureAssetTask;
  93007. }(AbstractAssetTask));
  93008. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93009. /**
  93010. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93011. */
  93012. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93013. __extends(HDRCubeTextureAssetTask, _super);
  93014. /**
  93015. * Creates a new HDRCubeTextureAssetTask object
  93016. * @param name defines the name of the task
  93017. * @param url defines the location of the file to load
  93018. * @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.
  93019. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93020. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93021. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  93022. * @param reserved Internal use only
  93023. */
  93024. function HDRCubeTextureAssetTask(
  93025. /**
  93026. * Defines the name of the task
  93027. */
  93028. name,
  93029. /**
  93030. * Defines the location of the file to load
  93031. */
  93032. url,
  93033. /**
  93034. * Defines the desired size (the more it increases the longer the generation will be)
  93035. */
  93036. size,
  93037. /**
  93038. * Defines if mipmaps should not be generated (default is false)
  93039. */
  93040. noMipmap,
  93041. /**
  93042. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93043. */
  93044. generateHarmonics,
  93045. /**
  93046. * 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)
  93047. */
  93048. gammaSpace,
  93049. /**
  93050. * Internal Use Only
  93051. */
  93052. reserved) {
  93053. if (noMipmap === void 0) { noMipmap = false; }
  93054. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93055. if (gammaSpace === void 0) { gammaSpace = false; }
  93056. if (reserved === void 0) { reserved = false; }
  93057. var _this = _super.call(this, name) || this;
  93058. _this.name = name;
  93059. _this.url = url;
  93060. _this.size = size;
  93061. _this.noMipmap = noMipmap;
  93062. _this.generateHarmonics = generateHarmonics;
  93063. _this.gammaSpace = gammaSpace;
  93064. _this.reserved = reserved;
  93065. return _this;
  93066. }
  93067. /**
  93068. * Execute the current task
  93069. * @param scene defines the scene where you want your assets to be loaded
  93070. * @param onSuccess is a callback called when the task is successfully executed
  93071. * @param onError is a callback called if an error occurs
  93072. */
  93073. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93074. var onload = function () {
  93075. onSuccess();
  93076. };
  93077. var onerror = function (message, exception) {
  93078. onError(message, exception);
  93079. };
  93080. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93081. };
  93082. return HDRCubeTextureAssetTask;
  93083. }(AbstractAssetTask));
  93084. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93085. /**
  93086. * This class can be used to easily import assets into a scene
  93087. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93088. */
  93089. var AssetsManager = /** @class */ (function () {
  93090. /**
  93091. * Creates a new AssetsManager
  93092. * @param scene defines the scene to work on
  93093. */
  93094. function AssetsManager(scene) {
  93095. this._isLoading = false;
  93096. this._tasks = new Array();
  93097. this._waitingTasksCount = 0;
  93098. this._totalTasksCount = 0;
  93099. /**
  93100. * Observable called when all tasks are processed
  93101. */
  93102. this.onTaskSuccessObservable = new BABYLON.Observable();
  93103. /**
  93104. * Observable called when a task had an error
  93105. */
  93106. this.onTaskErrorObservable = new BABYLON.Observable();
  93107. /**
  93108. * Observable called when a task is successful
  93109. */
  93110. this.onTasksDoneObservable = new BABYLON.Observable();
  93111. /**
  93112. * Observable called when a task is done (whatever the result is)
  93113. */
  93114. this.onProgressObservable = new BABYLON.Observable();
  93115. /**
  93116. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93117. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93118. */
  93119. this.useDefaultLoadingScreen = true;
  93120. this._scene = scene;
  93121. }
  93122. /**
  93123. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93124. * @param taskName defines the name of the new task
  93125. * @param meshesNames defines the name of meshes to load
  93126. * @param rootUrl defines the root url to use to locate files
  93127. * @param sceneFilename defines the filename of the scene file
  93128. * @returns a new {BABYLON.MeshAssetTask} object
  93129. */
  93130. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93131. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93132. this._tasks.push(task);
  93133. return task;
  93134. };
  93135. /**
  93136. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93137. * @param taskName defines the name of the new task
  93138. * @param url defines the url of the file to load
  93139. * @returns a new {BABYLON.TextFileAssetTask} object
  93140. */
  93141. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93142. var task = new TextFileAssetTask(taskName, url);
  93143. this._tasks.push(task);
  93144. return task;
  93145. };
  93146. /**
  93147. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93148. * @param taskName defines the name of the new task
  93149. * @param url defines the url of the file to load
  93150. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93151. */
  93152. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93153. var task = new BinaryFileAssetTask(taskName, url);
  93154. this._tasks.push(task);
  93155. return task;
  93156. };
  93157. /**
  93158. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93159. * @param taskName defines the name of the new task
  93160. * @param url defines the url of the file to load
  93161. * @returns a new {BABYLON.ImageAssetTask} object
  93162. */
  93163. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93164. var task = new ImageAssetTask(taskName, url);
  93165. this._tasks.push(task);
  93166. return task;
  93167. };
  93168. /**
  93169. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93170. * @param taskName defines the name of the new task
  93171. * @param url defines the url of the file to load
  93172. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93173. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93174. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93175. * @returns a new {BABYLON.TextureAssetTask} object
  93176. */
  93177. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93179. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93180. this._tasks.push(task);
  93181. return task;
  93182. };
  93183. /**
  93184. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93185. * @param taskName defines the name of the new task
  93186. * @param url defines the url of the file to load
  93187. * @param extensions defines the extension to use to load the cube map (can be null)
  93188. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93189. * @param files defines the list of files to load (can be null)
  93190. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93191. */
  93192. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93193. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93194. this._tasks.push(task);
  93195. return task;
  93196. };
  93197. /**
  93198. *
  93199. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93200. * @param taskName defines the name of the new task
  93201. * @param url defines the url of the file to load
  93202. * @param size defines the size you want for the cubemap (can be null)
  93203. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93204. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93205. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  93206. * @param reserved Internal use only
  93207. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93208. */
  93209. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93210. if (noMipmap === void 0) { noMipmap = false; }
  93211. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93212. if (gammaSpace === void 0) { gammaSpace = false; }
  93213. if (reserved === void 0) { reserved = false; }
  93214. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93215. this._tasks.push(task);
  93216. return task;
  93217. };
  93218. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93219. var _this = this;
  93220. this._waitingTasksCount--;
  93221. try {
  93222. if (task.taskState === AssetTaskState.DONE) {
  93223. // Let's remove successfull tasks
  93224. BABYLON.Tools.SetImmediate(function () {
  93225. var index = _this._tasks.indexOf(task);
  93226. if (index > -1) {
  93227. _this._tasks.splice(index, 1);
  93228. }
  93229. });
  93230. }
  93231. if (this.onProgress) {
  93232. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93233. }
  93234. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93235. }
  93236. catch (e) {
  93237. BABYLON.Tools.Error("Error running progress callbacks.");
  93238. console.log(e);
  93239. }
  93240. if (this._waitingTasksCount === 0) {
  93241. try {
  93242. if (this.onFinish) {
  93243. this.onFinish(this._tasks);
  93244. }
  93245. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93246. }
  93247. catch (e) {
  93248. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93249. console.log(e);
  93250. }
  93251. this._isLoading = false;
  93252. this._scene.getEngine().hideLoadingUI();
  93253. }
  93254. };
  93255. AssetsManager.prototype._runTask = function (task) {
  93256. var _this = this;
  93257. var done = function () {
  93258. try {
  93259. if (_this.onTaskSuccess) {
  93260. _this.onTaskSuccess(task);
  93261. }
  93262. _this.onTaskSuccessObservable.notifyObservers(task);
  93263. _this._decreaseWaitingTasksCount(task);
  93264. }
  93265. catch (e) {
  93266. error("Error executing task success callbacks", e);
  93267. }
  93268. };
  93269. var error = function (message, exception) {
  93270. task._setErrorObject(message, exception);
  93271. if (_this.onTaskError) {
  93272. _this.onTaskError(task);
  93273. }
  93274. _this.onTaskErrorObservable.notifyObservers(task);
  93275. _this._decreaseWaitingTasksCount(task);
  93276. };
  93277. task.run(this._scene, done, error);
  93278. };
  93279. /**
  93280. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93281. * @return the current instance of the {BABYLON.AssetsManager}
  93282. */
  93283. AssetsManager.prototype.reset = function () {
  93284. this._isLoading = false;
  93285. this._tasks = new Array();
  93286. return this;
  93287. };
  93288. /**
  93289. * Start the loading process
  93290. * @return the current instance of the {BABYLON.AssetsManager}
  93291. */
  93292. AssetsManager.prototype.load = function () {
  93293. if (this._isLoading) {
  93294. return this;
  93295. }
  93296. this._isLoading = true;
  93297. this._waitingTasksCount = this._tasks.length;
  93298. this._totalTasksCount = this._tasks.length;
  93299. if (this._waitingTasksCount === 0) {
  93300. this._isLoading = false;
  93301. if (this.onFinish) {
  93302. this.onFinish(this._tasks);
  93303. }
  93304. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93305. return this;
  93306. }
  93307. if (this.useDefaultLoadingScreen) {
  93308. this._scene.getEngine().displayLoadingUI();
  93309. }
  93310. for (var index = 0; index < this._tasks.length; index++) {
  93311. var task = this._tasks[index];
  93312. this._runTask(task);
  93313. }
  93314. return this;
  93315. };
  93316. return AssetsManager;
  93317. }());
  93318. BABYLON.AssetsManager = AssetsManager;
  93319. })(BABYLON || (BABYLON = {}));
  93320. //# sourceMappingURL=babylon.assetsManager.js.map
  93321. var BABYLON;
  93322. (function (BABYLON) {
  93323. var serializedGeometries = [];
  93324. var serializeGeometry = function (geometry, serializationGeometries) {
  93325. if (serializedGeometries[geometry.id]) {
  93326. return;
  93327. }
  93328. if (geometry.doNotSerialize) {
  93329. return;
  93330. }
  93331. if (geometry instanceof BABYLON.BoxGeometry) {
  93332. serializationGeometries.boxes.push(geometry.serialize());
  93333. }
  93334. else if (geometry instanceof BABYLON.SphereGeometry) {
  93335. serializationGeometries.spheres.push(geometry.serialize());
  93336. }
  93337. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93338. serializationGeometries.cylinders.push(geometry.serialize());
  93339. }
  93340. else if (geometry instanceof BABYLON.TorusGeometry) {
  93341. serializationGeometries.toruses.push(geometry.serialize());
  93342. }
  93343. else if (geometry instanceof BABYLON.GroundGeometry) {
  93344. serializationGeometries.grounds.push(geometry.serialize());
  93345. }
  93346. else if (geometry instanceof BABYLON.Plane) {
  93347. serializationGeometries.planes.push(geometry.serialize());
  93348. }
  93349. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93350. serializationGeometries.torusKnots.push(geometry.serialize());
  93351. }
  93352. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93353. throw new Error("Unknown primitive type");
  93354. }
  93355. else {
  93356. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93357. }
  93358. serializedGeometries[geometry.id] = true;
  93359. };
  93360. var serializeMesh = function (mesh, serializationScene) {
  93361. var serializationObject = {};
  93362. // Geometry
  93363. var geometry = mesh._geometry;
  93364. if (geometry) {
  93365. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93366. // 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
  93367. serializeGeometry(geometry, serializationScene.geometries);
  93368. }
  93369. }
  93370. // Custom
  93371. if (mesh.serialize) {
  93372. mesh.serialize(serializationObject);
  93373. }
  93374. return serializationObject;
  93375. };
  93376. var finalizeSingleMesh = function (mesh, serializationObject) {
  93377. //only works if the mesh is already loaded
  93378. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93379. //serialize material
  93380. if (mesh.material) {
  93381. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93382. serializationObject.materials = serializationObject.materials || [];
  93383. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93384. serializationObject.materials.push(mesh.material.serialize());
  93385. }
  93386. }
  93387. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93388. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93389. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93390. serializationObject.multiMaterials.push(mesh.material.serialize());
  93391. }
  93392. }
  93393. }
  93394. //serialize geometry
  93395. var geometry = mesh._geometry;
  93396. if (geometry) {
  93397. if (!serializationObject.geometries) {
  93398. serializationObject.geometries = {};
  93399. serializationObject.geometries.boxes = [];
  93400. serializationObject.geometries.spheres = [];
  93401. serializationObject.geometries.cylinders = [];
  93402. serializationObject.geometries.toruses = [];
  93403. serializationObject.geometries.grounds = [];
  93404. serializationObject.geometries.planes = [];
  93405. serializationObject.geometries.torusKnots = [];
  93406. serializationObject.geometries.vertexData = [];
  93407. }
  93408. serializeGeometry(geometry, serializationObject.geometries);
  93409. }
  93410. // Skeletons
  93411. if (mesh.skeleton) {
  93412. serializationObject.skeletons = serializationObject.skeletons || [];
  93413. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93414. }
  93415. //serialize the actual mesh
  93416. serializationObject.meshes = serializationObject.meshes || [];
  93417. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93418. }
  93419. };
  93420. var SceneSerializer = /** @class */ (function () {
  93421. function SceneSerializer() {
  93422. }
  93423. SceneSerializer.ClearCache = function () {
  93424. serializedGeometries = [];
  93425. };
  93426. SceneSerializer.Serialize = function (scene) {
  93427. var serializationObject = {};
  93428. SceneSerializer.ClearCache();
  93429. // Scene
  93430. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93431. serializationObject.autoClear = scene.autoClear;
  93432. serializationObject.clearColor = scene.clearColor.asArray();
  93433. serializationObject.ambientColor = scene.ambientColor.asArray();
  93434. serializationObject.gravity = scene.gravity.asArray();
  93435. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93436. serializationObject.workerCollisions = scene.workerCollisions;
  93437. // Fog
  93438. if (scene.fogMode && scene.fogMode !== 0) {
  93439. serializationObject.fogMode = scene.fogMode;
  93440. serializationObject.fogColor = scene.fogColor.asArray();
  93441. serializationObject.fogStart = scene.fogStart;
  93442. serializationObject.fogEnd = scene.fogEnd;
  93443. serializationObject.fogDensity = scene.fogDensity;
  93444. }
  93445. //Physics
  93446. if (scene.isPhysicsEnabled()) {
  93447. var physicEngine = scene.getPhysicsEngine();
  93448. if (physicEngine) {
  93449. serializationObject.physicsEnabled = true;
  93450. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93451. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93452. }
  93453. }
  93454. // Metadata
  93455. if (scene.metadata) {
  93456. serializationObject.metadata = scene.metadata;
  93457. }
  93458. // Morph targets
  93459. serializationObject.morphTargetManagers = [];
  93460. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93461. var abstractMesh = _a[_i];
  93462. var manager = abstractMesh.morphTargetManager;
  93463. if (manager) {
  93464. serializationObject.morphTargetManagers.push(manager.serialize());
  93465. }
  93466. }
  93467. // Lights
  93468. serializationObject.lights = [];
  93469. var index;
  93470. var light;
  93471. for (index = 0; index < scene.lights.length; index++) {
  93472. light = scene.lights[index];
  93473. if (!light.doNotSerialize) {
  93474. serializationObject.lights.push(light.serialize());
  93475. }
  93476. }
  93477. // Cameras
  93478. serializationObject.cameras = [];
  93479. for (index = 0; index < scene.cameras.length; index++) {
  93480. var camera = scene.cameras[index];
  93481. if (!camera.doNotSerialize) {
  93482. serializationObject.cameras.push(camera.serialize());
  93483. }
  93484. }
  93485. if (scene.activeCamera) {
  93486. serializationObject.activeCameraID = scene.activeCamera.id;
  93487. }
  93488. // Animations
  93489. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93490. // Materials
  93491. serializationObject.materials = [];
  93492. serializationObject.multiMaterials = [];
  93493. var material;
  93494. for (index = 0; index < scene.materials.length; index++) {
  93495. material = scene.materials[index];
  93496. if (!material.doNotSerialize) {
  93497. serializationObject.materials.push(material.serialize());
  93498. }
  93499. }
  93500. // MultiMaterials
  93501. serializationObject.multiMaterials = [];
  93502. for (index = 0; index < scene.multiMaterials.length; index++) {
  93503. var multiMaterial = scene.multiMaterials[index];
  93504. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93505. }
  93506. // Environment texture
  93507. if (scene.environmentTexture) {
  93508. serializationObject.environmentTexture = scene.environmentTexture.name;
  93509. }
  93510. // Skeletons
  93511. serializationObject.skeletons = [];
  93512. for (index = 0; index < scene.skeletons.length; index++) {
  93513. var skeleton = scene.skeletons[index];
  93514. if (!skeleton.doNotSerialize) {
  93515. serializationObject.skeletons.push(skeleton.serialize());
  93516. }
  93517. }
  93518. // Transform nodes
  93519. serializationObject.transformNodes = [];
  93520. for (index = 0; index < scene.transformNodes.length; index++) {
  93521. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93522. }
  93523. // Geometries
  93524. serializationObject.geometries = {};
  93525. serializationObject.geometries.boxes = [];
  93526. serializationObject.geometries.spheres = [];
  93527. serializationObject.geometries.cylinders = [];
  93528. serializationObject.geometries.toruses = [];
  93529. serializationObject.geometries.grounds = [];
  93530. serializationObject.geometries.planes = [];
  93531. serializationObject.geometries.torusKnots = [];
  93532. serializationObject.geometries.vertexData = [];
  93533. serializedGeometries = [];
  93534. var geometries = scene.getGeometries();
  93535. for (index = 0; index < geometries.length; index++) {
  93536. var geometry = geometries[index];
  93537. if (geometry.isReady()) {
  93538. serializeGeometry(geometry, serializationObject.geometries);
  93539. }
  93540. }
  93541. // Meshes
  93542. serializationObject.meshes = [];
  93543. for (index = 0; index < scene.meshes.length; index++) {
  93544. var abstractMesh = scene.meshes[index];
  93545. if (abstractMesh instanceof BABYLON.Mesh) {
  93546. var mesh = abstractMesh;
  93547. if (!mesh.doNotSerialize) {
  93548. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93549. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93550. }
  93551. }
  93552. }
  93553. }
  93554. // Particles Systems
  93555. serializationObject.particleSystems = [];
  93556. for (index = 0; index < scene.particleSystems.length; index++) {
  93557. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93558. }
  93559. // Lens flares
  93560. serializationObject.lensFlareSystems = [];
  93561. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93562. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93563. }
  93564. // Shadows
  93565. serializationObject.shadowGenerators = [];
  93566. for (index = 0; index < scene.lights.length; index++) {
  93567. light = scene.lights[index];
  93568. var shadowGenerator = light.getShadowGenerator();
  93569. if (shadowGenerator) {
  93570. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93571. }
  93572. }
  93573. // Action Manager
  93574. if (scene.actionManager) {
  93575. serializationObject.actions = scene.actionManager.serialize("scene");
  93576. }
  93577. // Audio
  93578. serializationObject.sounds = [];
  93579. for (index = 0; index < scene.soundTracks.length; index++) {
  93580. var soundtrack = scene.soundTracks[index];
  93581. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93582. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93583. }
  93584. }
  93585. // Effect layers
  93586. serializationObject.effectLayers = [];
  93587. for (index = 0; index < scene.effectLayers.length; index++) {
  93588. var layer = scene.effectLayers[index];
  93589. if (layer.serialize) {
  93590. serializationObject.effectLayers.push(layer.serialize());
  93591. }
  93592. }
  93593. return serializationObject;
  93594. };
  93595. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93596. if (withParents === void 0) { withParents = false; }
  93597. if (withChildren === void 0) { withChildren = false; }
  93598. var serializationObject = {};
  93599. SceneSerializer.ClearCache();
  93600. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93601. if (withParents || withChildren) {
  93602. //deliberate for loop! not for each, appended should be processed as well.
  93603. for (var i = 0; i < toSerialize.length; ++i) {
  93604. if (withChildren) {
  93605. toSerialize[i].getDescendants().forEach(function (node) {
  93606. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93607. toSerialize.push(node);
  93608. }
  93609. });
  93610. }
  93611. //make sure the array doesn't contain the object already
  93612. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93613. toSerialize.push(toSerialize[i].parent);
  93614. }
  93615. }
  93616. }
  93617. toSerialize.forEach(function (mesh) {
  93618. finalizeSingleMesh(mesh, serializationObject);
  93619. });
  93620. return serializationObject;
  93621. };
  93622. return SceneSerializer;
  93623. }());
  93624. BABYLON.SceneSerializer = SceneSerializer;
  93625. })(BABYLON || (BABYLON = {}));
  93626. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93627. var BABYLON;
  93628. (function (BABYLON) {
  93629. var ReflectionProbe = /** @class */ (function () {
  93630. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93631. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93632. var _this = this;
  93633. this.name = name;
  93634. this._viewMatrix = BABYLON.Matrix.Identity();
  93635. this._target = BABYLON.Vector3.Zero();
  93636. this._add = BABYLON.Vector3.Zero();
  93637. this._invertYAxis = false;
  93638. this.position = BABYLON.Vector3.Zero();
  93639. this._scene = scene;
  93640. this._scene.reflectionProbes.push(this);
  93641. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93642. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93643. switch (faceIndex) {
  93644. case 0:
  93645. _this._add.copyFromFloats(1, 0, 0);
  93646. break;
  93647. case 1:
  93648. _this._add.copyFromFloats(-1, 0, 0);
  93649. break;
  93650. case 2:
  93651. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93652. break;
  93653. case 3:
  93654. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93655. break;
  93656. case 4:
  93657. _this._add.copyFromFloats(0, 0, 1);
  93658. break;
  93659. case 5:
  93660. _this._add.copyFromFloats(0, 0, -1);
  93661. break;
  93662. }
  93663. if (_this._attachedMesh) {
  93664. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93665. }
  93666. _this.position.addToRef(_this._add, _this._target);
  93667. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93668. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93669. scene._forcedViewPosition = _this.position;
  93670. });
  93671. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93672. scene._forcedViewPosition = null;
  93673. scene.updateTransformMatrix(true);
  93674. });
  93675. if (scene.activeCamera) {
  93676. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93677. }
  93678. }
  93679. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93680. get: function () {
  93681. return this._renderTargetTexture.samples;
  93682. },
  93683. set: function (value) {
  93684. this._renderTargetTexture.samples = value;
  93685. },
  93686. enumerable: true,
  93687. configurable: true
  93688. });
  93689. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93690. get: function () {
  93691. return this._renderTargetTexture.refreshRate;
  93692. },
  93693. set: function (value) {
  93694. this._renderTargetTexture.refreshRate = value;
  93695. },
  93696. enumerable: true,
  93697. configurable: true
  93698. });
  93699. ReflectionProbe.prototype.getScene = function () {
  93700. return this._scene;
  93701. };
  93702. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93703. get: function () {
  93704. return this._renderTargetTexture;
  93705. },
  93706. enumerable: true,
  93707. configurable: true
  93708. });
  93709. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93710. get: function () {
  93711. return this._renderTargetTexture.renderList;
  93712. },
  93713. enumerable: true,
  93714. configurable: true
  93715. });
  93716. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93717. this._attachedMesh = mesh;
  93718. };
  93719. /**
  93720. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93721. *
  93722. * @param renderingGroupId The rendering group id corresponding to its index
  93723. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93724. */
  93725. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93726. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93727. };
  93728. ReflectionProbe.prototype.dispose = function () {
  93729. var index = this._scene.reflectionProbes.indexOf(this);
  93730. if (index !== -1) {
  93731. // Remove from the scene if found
  93732. this._scene.reflectionProbes.splice(index, 1);
  93733. }
  93734. if (this._renderTargetTexture) {
  93735. this._renderTargetTexture.dispose();
  93736. this._renderTargetTexture = null;
  93737. }
  93738. };
  93739. return ReflectionProbe;
  93740. }());
  93741. BABYLON.ReflectionProbe = ReflectionProbe;
  93742. })(BABYLON || (BABYLON = {}));
  93743. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93744. var BABYLON;
  93745. (function (BABYLON) {
  93746. var Layer = /** @class */ (function () {
  93747. function Layer(name, imgUrl, scene, isBackground, color) {
  93748. this.name = name;
  93749. this.scale = new BABYLON.Vector2(1, 1);
  93750. this.offset = new BABYLON.Vector2(0, 0);
  93751. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93752. this.layerMask = 0x0FFFFFFF;
  93753. this._vertexBuffers = {};
  93754. // Events
  93755. /**
  93756. * An event triggered when the layer is disposed.
  93757. */
  93758. this.onDisposeObservable = new BABYLON.Observable();
  93759. /**
  93760. * An event triggered before rendering the scene
  93761. */
  93762. this.onBeforeRenderObservable = new BABYLON.Observable();
  93763. /**
  93764. * An event triggered after rendering the scene
  93765. */
  93766. this.onAfterRenderObservable = new BABYLON.Observable();
  93767. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93768. this.isBackground = isBackground === undefined ? true : isBackground;
  93769. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93770. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93771. this._scene.layers.push(this);
  93772. var engine = this._scene.getEngine();
  93773. // VBO
  93774. var vertices = [];
  93775. vertices.push(1, 1);
  93776. vertices.push(-1, 1);
  93777. vertices.push(-1, -1);
  93778. vertices.push(1, -1);
  93779. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93780. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93781. this._createIndexBuffer();
  93782. // Effects
  93783. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93784. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93785. }
  93786. Object.defineProperty(Layer.prototype, "onDispose", {
  93787. set: function (callback) {
  93788. if (this._onDisposeObserver) {
  93789. this.onDisposeObservable.remove(this._onDisposeObserver);
  93790. }
  93791. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93792. },
  93793. enumerable: true,
  93794. configurable: true
  93795. });
  93796. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93797. set: function (callback) {
  93798. if (this._onBeforeRenderObserver) {
  93799. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93800. }
  93801. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93802. },
  93803. enumerable: true,
  93804. configurable: true
  93805. });
  93806. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93807. set: function (callback) {
  93808. if (this._onAfterRenderObserver) {
  93809. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93810. }
  93811. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93812. },
  93813. enumerable: true,
  93814. configurable: true
  93815. });
  93816. Layer.prototype._createIndexBuffer = function () {
  93817. var engine = this._scene.getEngine();
  93818. // Indices
  93819. var indices = [];
  93820. indices.push(0);
  93821. indices.push(1);
  93822. indices.push(2);
  93823. indices.push(0);
  93824. indices.push(2);
  93825. indices.push(3);
  93826. this._indexBuffer = engine.createIndexBuffer(indices);
  93827. };
  93828. Layer.prototype._rebuild = function () {
  93829. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93830. if (vb) {
  93831. vb._rebuild();
  93832. }
  93833. this._createIndexBuffer();
  93834. };
  93835. Layer.prototype.render = function () {
  93836. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93837. // Check
  93838. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93839. return;
  93840. var engine = this._scene.getEngine();
  93841. this.onBeforeRenderObservable.notifyObservers(this);
  93842. // Render
  93843. engine.enableEffect(currentEffect);
  93844. engine.setState(false);
  93845. // Texture
  93846. currentEffect.setTexture("textureSampler", this.texture);
  93847. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93848. // Color
  93849. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93850. // Scale / offset
  93851. currentEffect.setVector2("offset", this.offset);
  93852. currentEffect.setVector2("scale", this.scale);
  93853. // VBOs
  93854. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93855. // Draw order
  93856. if (!this.alphaTest) {
  93857. engine.setAlphaMode(this.alphaBlendingMode);
  93858. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93859. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93860. }
  93861. else {
  93862. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93863. }
  93864. this.onAfterRenderObservable.notifyObservers(this);
  93865. };
  93866. Layer.prototype.dispose = function () {
  93867. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93868. if (vertexBuffer) {
  93869. vertexBuffer.dispose();
  93870. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93871. }
  93872. if (this._indexBuffer) {
  93873. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93874. this._indexBuffer = null;
  93875. }
  93876. if (this.texture) {
  93877. this.texture.dispose();
  93878. this.texture = null;
  93879. }
  93880. // Remove from scene
  93881. var index = this._scene.layers.indexOf(this);
  93882. this._scene.layers.splice(index, 1);
  93883. // Callback
  93884. this.onDisposeObservable.notifyObservers(this);
  93885. this.onDisposeObservable.clear();
  93886. this.onAfterRenderObservable.clear();
  93887. this.onBeforeRenderObservable.clear();
  93888. };
  93889. return Layer;
  93890. }());
  93891. BABYLON.Layer = Layer;
  93892. })(BABYLON || (BABYLON = {}));
  93893. //# sourceMappingURL=babylon.layer.js.map
  93894. var BABYLON;
  93895. (function (BABYLON) {
  93896. var TextureTools = /** @class */ (function () {
  93897. function TextureTools() {
  93898. }
  93899. /**
  93900. * Uses the GPU to create a copy texture rescaled at a given size
  93901. * @param texture Texture to copy from
  93902. * @param width Desired width
  93903. * @param height Desired height
  93904. * @return Generated texture
  93905. */
  93906. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  93907. if (useBilinearMode === void 0) { useBilinearMode = true; }
  93908. var scene = texture.getScene();
  93909. var engine = scene.getEngine();
  93910. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  93911. rtt.wrapU = texture.wrapU;
  93912. rtt.wrapV = texture.wrapV;
  93913. rtt.uOffset = texture.uOffset;
  93914. rtt.vOffset = texture.vOffset;
  93915. rtt.uScale = texture.uScale;
  93916. rtt.vScale = texture.vScale;
  93917. rtt.uAng = texture.uAng;
  93918. rtt.vAng = texture.vAng;
  93919. rtt.wAng = texture.wAng;
  93920. rtt.coordinatesIndex = texture.coordinatesIndex;
  93921. rtt.level = texture.level;
  93922. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  93923. rtt._texture.isReady = false;
  93924. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93925. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93926. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93927. passPostProcess.getEffect().executeWhenCompiled(function () {
  93928. passPostProcess.onApply = function (effect) {
  93929. effect.setTexture("textureSampler", texture);
  93930. };
  93931. var internalTexture = rtt.getInternalTexture();
  93932. if (internalTexture) {
  93933. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  93934. engine.unBindFramebuffer(internalTexture);
  93935. rtt.disposeFramebufferObjects();
  93936. passPostProcess.dispose();
  93937. internalTexture.isReady = true;
  93938. }
  93939. });
  93940. return rtt;
  93941. };
  93942. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  93943. if (!scene._environmentBRDFTexture) {
  93944. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93945. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93946. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93947. scene._environmentBRDFTexture = texture;
  93948. }
  93949. return scene._environmentBRDFTexture;
  93950. };
  93951. 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=";
  93952. return TextureTools;
  93953. }());
  93954. BABYLON.TextureTools = TextureTools;
  93955. })(BABYLON || (BABYLON = {}));
  93956. //# sourceMappingURL=babylon.textureTools.js.map
  93957. var BABYLON;
  93958. (function (BABYLON) {
  93959. var FramingBehavior = /** @class */ (function () {
  93960. function FramingBehavior() {
  93961. this._mode = FramingBehavior.FitFrustumSidesMode;
  93962. this._radiusScale = 1.0;
  93963. this._positionScale = 0.5;
  93964. this._defaultElevation = 0.3;
  93965. this._elevationReturnTime = 1500;
  93966. this._elevationReturnWaitTime = 1000;
  93967. this._zoomStopsAnimation = false;
  93968. this._framingTime = 1500;
  93969. this._isPointerDown = false;
  93970. this._lastInteractionTime = -Infinity;
  93971. // Framing control
  93972. this._animatables = new Array();
  93973. this._betaIsAnimating = false;
  93974. }
  93975. Object.defineProperty(FramingBehavior.prototype, "name", {
  93976. get: function () {
  93977. return "Framing";
  93978. },
  93979. enumerable: true,
  93980. configurable: true
  93981. });
  93982. Object.defineProperty(FramingBehavior.prototype, "mode", {
  93983. /**
  93984. * Gets current mode used by the behavior.
  93985. */
  93986. get: function () {
  93987. return this._mode;
  93988. },
  93989. /**
  93990. * Sets the current mode used by the behavior
  93991. */
  93992. set: function (mode) {
  93993. this._mode = mode;
  93994. },
  93995. enumerable: true,
  93996. configurable: true
  93997. });
  93998. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  93999. /**
  94000. * Gets the scale applied to the radius
  94001. */
  94002. get: function () {
  94003. return this._radiusScale;
  94004. },
  94005. /**
  94006. * Sets the scale applied to the radius (1 by default)
  94007. */
  94008. set: function (radius) {
  94009. this._radiusScale = radius;
  94010. },
  94011. enumerable: true,
  94012. configurable: true
  94013. });
  94014. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94015. /**
  94016. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94017. */
  94018. get: function () {
  94019. return this._positionScale;
  94020. },
  94021. /**
  94022. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94023. */
  94024. set: function (scale) {
  94025. this._positionScale = scale;
  94026. },
  94027. enumerable: true,
  94028. configurable: true
  94029. });
  94030. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94031. /**
  94032. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94033. * behaviour is triggered, in radians.
  94034. */
  94035. get: function () {
  94036. return this._defaultElevation;
  94037. },
  94038. /**
  94039. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94040. * behaviour is triggered, in radians.
  94041. */
  94042. set: function (elevation) {
  94043. this._defaultElevation = elevation;
  94044. },
  94045. enumerable: true,
  94046. configurable: true
  94047. });
  94048. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94049. /**
  94050. * Gets the time (in milliseconds) taken to return to the default beta position.
  94051. * Negative value indicates camera should not return to default.
  94052. */
  94053. get: function () {
  94054. return this._elevationReturnTime;
  94055. },
  94056. /**
  94057. * Sets the time (in milliseconds) taken to return to the default beta position.
  94058. * Negative value indicates camera should not return to default.
  94059. */
  94060. set: function (speed) {
  94061. this._elevationReturnTime = speed;
  94062. },
  94063. enumerable: true,
  94064. configurable: true
  94065. });
  94066. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94067. /**
  94068. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94069. */
  94070. get: function () {
  94071. return this._elevationReturnWaitTime;
  94072. },
  94073. /**
  94074. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94075. */
  94076. set: function (time) {
  94077. this._elevationReturnWaitTime = time;
  94078. },
  94079. enumerable: true,
  94080. configurable: true
  94081. });
  94082. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94083. /**
  94084. * Gets the flag that indicates if user zooming should stop animation.
  94085. */
  94086. get: function () {
  94087. return this._zoomStopsAnimation;
  94088. },
  94089. /**
  94090. * Sets the flag that indicates if user zooming should stop animation.
  94091. */
  94092. set: function (flag) {
  94093. this._zoomStopsAnimation = flag;
  94094. },
  94095. enumerable: true,
  94096. configurable: true
  94097. });
  94098. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94099. /**
  94100. * Gets the transition time when framing the mesh, in milliseconds
  94101. */
  94102. get: function () {
  94103. return this._framingTime;
  94104. },
  94105. /**
  94106. * Sets the transition time when framing the mesh, in milliseconds
  94107. */
  94108. set: function (time) {
  94109. this._framingTime = time;
  94110. },
  94111. enumerable: true,
  94112. configurable: true
  94113. });
  94114. FramingBehavior.prototype.init = function () {
  94115. // Do notihng
  94116. };
  94117. FramingBehavior.prototype.attach = function (camera) {
  94118. var _this = this;
  94119. this._attachedCamera = camera;
  94120. var scene = this._attachedCamera.getScene();
  94121. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94122. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94123. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94124. _this._isPointerDown = true;
  94125. return;
  94126. }
  94127. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94128. _this._isPointerDown = false;
  94129. }
  94130. });
  94131. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94132. if (mesh) {
  94133. _this.zoomOnMesh(mesh);
  94134. }
  94135. });
  94136. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94137. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94138. _this._applyUserInteraction();
  94139. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94140. // back to the default position after a given timeout
  94141. _this._maintainCameraAboveGround();
  94142. });
  94143. };
  94144. FramingBehavior.prototype.detach = function () {
  94145. if (!this._attachedCamera) {
  94146. return;
  94147. }
  94148. var scene = this._attachedCamera.getScene();
  94149. if (this._onPrePointerObservableObserver) {
  94150. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94151. }
  94152. if (this._onAfterCheckInputsObserver) {
  94153. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94154. }
  94155. if (this._onMeshTargetChangedObserver) {
  94156. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94157. }
  94158. this._attachedCamera = null;
  94159. };
  94160. /**
  94161. * Targets the given mesh and updates zoom level accordingly.
  94162. * @param mesh The mesh to target.
  94163. * @param radius Optional. If a cached radius position already exists, overrides default.
  94164. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94165. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94166. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94167. */
  94168. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94169. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94170. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94171. mesh.computeWorldMatrix(true);
  94172. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94173. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94174. };
  94175. /**
  94176. * Targets the given mesh with its children and updates zoom level accordingly.
  94177. * @param mesh The mesh to target.
  94178. * @param radius Optional. If a cached radius position already exists, overrides default.
  94179. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94180. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94181. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94182. */
  94183. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94184. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94185. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94186. mesh.computeWorldMatrix(true);
  94187. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94188. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94189. };
  94190. /**
  94191. * Targets the given meshes with their children and updates zoom level accordingly.
  94192. * @param meshes The mesh to target.
  94193. * @param radius Optional. If a cached radius position already exists, overrides default.
  94194. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94195. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94196. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94197. */
  94198. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94199. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94200. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94201. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94202. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94203. for (var i = 0; i < meshes.length; i++) {
  94204. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94205. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94206. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94207. }
  94208. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94209. };
  94210. /**
  94211. * Targets the given mesh and updates zoom level accordingly.
  94212. * @param mesh The mesh to target.
  94213. * @param radius Optional. If a cached radius position already exists, overrides default.
  94214. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94215. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94216. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94217. */
  94218. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94219. var _this = this;
  94220. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94221. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94222. var zoomTarget;
  94223. if (!this._attachedCamera) {
  94224. return;
  94225. }
  94226. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94227. var bottom = minimumWorld.y;
  94228. var top = maximumWorld.y;
  94229. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94230. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94231. if (focusOnOriginXZ) {
  94232. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94233. }
  94234. else {
  94235. var centerWorld = minimumWorld.add(radiusWorld);
  94236. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94237. }
  94238. if (!this._vectorTransition) {
  94239. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94240. }
  94241. this._betaIsAnimating = true;
  94242. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94243. if (animatable) {
  94244. this._animatables.push(animatable);
  94245. }
  94246. // sets the radius and lower radius bounds
  94247. // Small delta ensures camera is not always at lower zoom limit.
  94248. var radius = 0;
  94249. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94250. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94251. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94252. radius = position;
  94253. }
  94254. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94255. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94256. if (this._attachedCamera.lowerRadiusLimit === null) {
  94257. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94258. }
  94259. }
  94260. // Set sensibilities
  94261. var extend = maximumWorld.subtract(minimumWorld).length();
  94262. this._attachedCamera.panningSensibility = 5000 / extend;
  94263. this._attachedCamera.wheelPrecision = 100 / radius;
  94264. // transition to new radius
  94265. if (!this._radiusTransition) {
  94266. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94267. }
  94268. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94269. _this.stopAllAnimations();
  94270. if (onAnimationEnd) {
  94271. onAnimationEnd();
  94272. }
  94273. if (_this._attachedCamera) {
  94274. _this._attachedCamera.storeState();
  94275. }
  94276. });
  94277. if (animatable) {
  94278. this._animatables.push(animatable);
  94279. }
  94280. };
  94281. /**
  94282. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94283. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94284. * frustum width.
  94285. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94286. * to fully enclose the mesh in the viewing frustum.
  94287. */
  94288. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94289. var size = maximumWorld.subtract(minimumWorld);
  94290. var boxVectorGlobalDiagonal = size.length();
  94291. var frustumSlope = this._getFrustumSlope();
  94292. // Formula for setting distance
  94293. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94294. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94295. // Horizon distance
  94296. var radius = radiusWithoutFraming * this._radiusScale;
  94297. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94298. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94299. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94300. var camera = this._attachedCamera;
  94301. if (!camera) {
  94302. return 0;
  94303. }
  94304. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94305. // Don't exceed the requested limit
  94306. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94307. }
  94308. // Don't exceed the upper radius limit
  94309. if (camera.upperRadiusLimit) {
  94310. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94311. }
  94312. return distance;
  94313. };
  94314. /**
  94315. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94316. * is automatically returned to its default position (expected to be above ground plane).
  94317. */
  94318. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94319. var _this = this;
  94320. if (this._elevationReturnTime < 0) {
  94321. return;
  94322. }
  94323. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94324. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94325. var limitBeta = Math.PI * 0.5;
  94326. // Bring the camera back up if below the ground plane
  94327. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94328. this._betaIsAnimating = true;
  94329. //Transition to new position
  94330. this.stopAllAnimations();
  94331. if (!this._betaTransition) {
  94332. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94333. }
  94334. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94335. _this._clearAnimationLocks();
  94336. _this.stopAllAnimations();
  94337. });
  94338. if (animatabe) {
  94339. this._animatables.push(animatabe);
  94340. }
  94341. }
  94342. };
  94343. /**
  94344. * Returns the frustum slope based on the canvas ratio and camera FOV
  94345. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94346. */
  94347. FramingBehavior.prototype._getFrustumSlope = function () {
  94348. // Calculate the viewport ratio
  94349. // Aspect Ratio is Height/Width.
  94350. var camera = this._attachedCamera;
  94351. if (!camera) {
  94352. return BABYLON.Vector2.Zero();
  94353. }
  94354. var engine = camera.getScene().getEngine();
  94355. var aspectRatio = engine.getAspectRatio(camera);
  94356. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94357. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94358. var frustumSlopeY = Math.tan(camera.fov / 2);
  94359. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94360. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94361. // along the forward vector.
  94362. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94363. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94364. };
  94365. /**
  94366. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94367. */
  94368. FramingBehavior.prototype._clearAnimationLocks = function () {
  94369. this._betaIsAnimating = false;
  94370. };
  94371. /**
  94372. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94373. */
  94374. FramingBehavior.prototype._applyUserInteraction = function () {
  94375. if (this.isUserIsMoving) {
  94376. this._lastInteractionTime = BABYLON.Tools.Now;
  94377. this.stopAllAnimations();
  94378. this._clearAnimationLocks();
  94379. }
  94380. };
  94381. /**
  94382. * Stops and removes all animations that have been applied to the camera
  94383. */
  94384. FramingBehavior.prototype.stopAllAnimations = function () {
  94385. if (this._attachedCamera) {
  94386. this._attachedCamera.animations = [];
  94387. }
  94388. while (this._animatables.length) {
  94389. if (this._animatables[0]) {
  94390. this._animatables[0].onAnimationEnd = null;
  94391. this._animatables[0].stop();
  94392. }
  94393. this._animatables.shift();
  94394. }
  94395. };
  94396. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94397. /**
  94398. * Gets a value indicating if the user is moving the camera
  94399. */
  94400. get: function () {
  94401. if (!this._attachedCamera) {
  94402. return false;
  94403. }
  94404. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94405. this._attachedCamera.inertialBetaOffset !== 0 ||
  94406. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94407. this._attachedCamera.inertialPanningX !== 0 ||
  94408. this._attachedCamera.inertialPanningY !== 0 ||
  94409. this._isPointerDown;
  94410. },
  94411. enumerable: true,
  94412. configurable: true
  94413. });
  94414. /**
  94415. * The easing function used by animations
  94416. */
  94417. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94418. /**
  94419. * The easing mode used by animations
  94420. */
  94421. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94422. // Statics
  94423. /**
  94424. * The camera can move all the way towards the mesh.
  94425. */
  94426. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94427. /**
  94428. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94429. */
  94430. FramingBehavior.FitFrustumSidesMode = 1;
  94431. return FramingBehavior;
  94432. }());
  94433. BABYLON.FramingBehavior = FramingBehavior;
  94434. })(BABYLON || (BABYLON = {}));
  94435. //# sourceMappingURL=babylon.framingBehavior.js.map
  94436. var BABYLON;
  94437. (function (BABYLON) {
  94438. /**
  94439. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94440. */
  94441. var BouncingBehavior = /** @class */ (function () {
  94442. function BouncingBehavior() {
  94443. /**
  94444. * The duration of the animation, in milliseconds
  94445. */
  94446. this.transitionDuration = 450;
  94447. /**
  94448. * Length of the distance animated by the transition when lower radius is reached
  94449. */
  94450. this.lowerRadiusTransitionRange = 2;
  94451. /**
  94452. * Length of the distance animated by the transition when upper radius is reached
  94453. */
  94454. this.upperRadiusTransitionRange = -2;
  94455. this._autoTransitionRange = false;
  94456. // Animations
  94457. this._radiusIsAnimating = false;
  94458. this._radiusBounceTransition = null;
  94459. this._animatables = new Array();
  94460. }
  94461. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94462. get: function () {
  94463. return "Bouncing";
  94464. },
  94465. enumerable: true,
  94466. configurable: true
  94467. });
  94468. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94469. /**
  94470. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94471. */
  94472. get: function () {
  94473. return this._autoTransitionRange;
  94474. },
  94475. /**
  94476. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94477. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94478. */
  94479. set: function (value) {
  94480. var _this = this;
  94481. if (this._autoTransitionRange === value) {
  94482. return;
  94483. }
  94484. this._autoTransitionRange = value;
  94485. var camera = this._attachedCamera;
  94486. if (!camera) {
  94487. return;
  94488. }
  94489. if (value) {
  94490. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94491. if (!mesh) {
  94492. return;
  94493. }
  94494. mesh.computeWorldMatrix(true);
  94495. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94496. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94497. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94498. });
  94499. }
  94500. else if (this._onMeshTargetChangedObserver) {
  94501. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94502. }
  94503. },
  94504. enumerable: true,
  94505. configurable: true
  94506. });
  94507. BouncingBehavior.prototype.init = function () {
  94508. // Do notihng
  94509. };
  94510. BouncingBehavior.prototype.attach = function (camera) {
  94511. var _this = this;
  94512. this._attachedCamera = camera;
  94513. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94514. if (!_this._attachedCamera) {
  94515. return;
  94516. }
  94517. // Add the bounce animation to the lower radius limit
  94518. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94519. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94520. }
  94521. // Add the bounce animation to the upper radius limit
  94522. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94523. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94524. }
  94525. });
  94526. };
  94527. BouncingBehavior.prototype.detach = function () {
  94528. if (!this._attachedCamera) {
  94529. return;
  94530. }
  94531. if (this._onAfterCheckInputsObserver) {
  94532. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94533. }
  94534. if (this._onMeshTargetChangedObserver) {
  94535. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94536. }
  94537. this._attachedCamera = null;
  94538. };
  94539. /**
  94540. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94541. * @param radiusLimit The limit to check against.
  94542. * @return Bool to indicate if at limit.
  94543. */
  94544. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94545. if (!this._attachedCamera) {
  94546. return false;
  94547. }
  94548. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94549. return true;
  94550. }
  94551. return false;
  94552. };
  94553. /**
  94554. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94555. * @param radiusDelta The delta by which to animate to. Can be negative.
  94556. */
  94557. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94558. var _this = this;
  94559. if (!this._attachedCamera) {
  94560. return;
  94561. }
  94562. if (!this._radiusBounceTransition) {
  94563. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94564. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94565. }
  94566. // Prevent zoom until bounce has completed
  94567. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94568. this._attachedCamera.wheelPrecision = Infinity;
  94569. this._attachedCamera.inertialRadiusOffset = 0;
  94570. // Animate to the radius limit
  94571. this.stopAllAnimations();
  94572. this._radiusIsAnimating = true;
  94573. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94574. if (animatable) {
  94575. this._animatables.push(animatable);
  94576. }
  94577. };
  94578. /**
  94579. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94580. */
  94581. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94582. this._radiusIsAnimating = false;
  94583. if (this._attachedCamera) {
  94584. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94585. }
  94586. };
  94587. /**
  94588. * Stops and removes all animations that have been applied to the camera
  94589. */
  94590. BouncingBehavior.prototype.stopAllAnimations = function () {
  94591. if (this._attachedCamera) {
  94592. this._attachedCamera.animations = [];
  94593. }
  94594. while (this._animatables.length) {
  94595. this._animatables[0].onAnimationEnd = null;
  94596. this._animatables[0].stop();
  94597. this._animatables.shift();
  94598. }
  94599. };
  94600. /**
  94601. * The easing function used by animations
  94602. */
  94603. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94604. /**
  94605. * The easing mode used by animations
  94606. */
  94607. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94608. return BouncingBehavior;
  94609. }());
  94610. BABYLON.BouncingBehavior = BouncingBehavior;
  94611. })(BABYLON || (BABYLON = {}));
  94612. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94613. var BABYLON;
  94614. (function (BABYLON) {
  94615. var AutoRotationBehavior = /** @class */ (function () {
  94616. function AutoRotationBehavior() {
  94617. this._zoomStopsAnimation = false;
  94618. this._idleRotationSpeed = 0.05;
  94619. this._idleRotationWaitTime = 2000;
  94620. this._idleRotationSpinupTime = 2000;
  94621. this._isPointerDown = false;
  94622. this._lastFrameTime = null;
  94623. this._lastInteractionTime = -Infinity;
  94624. this._cameraRotationSpeed = 0;
  94625. this._lastFrameRadius = 0;
  94626. }
  94627. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94628. get: function () {
  94629. return "AutoRotation";
  94630. },
  94631. enumerable: true,
  94632. configurable: true
  94633. });
  94634. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94635. /**
  94636. * Gets the flag that indicates if user zooming should stop animation.
  94637. */
  94638. get: function () {
  94639. return this._zoomStopsAnimation;
  94640. },
  94641. /**
  94642. * Sets the flag that indicates if user zooming should stop animation.
  94643. */
  94644. set: function (flag) {
  94645. this._zoomStopsAnimation = flag;
  94646. },
  94647. enumerable: true,
  94648. configurable: true
  94649. });
  94650. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94651. /**
  94652. * Gets the default speed at which the camera rotates around the model.
  94653. */
  94654. get: function () {
  94655. return this._idleRotationSpeed;
  94656. },
  94657. /**
  94658. * Sets the default speed at which the camera rotates around the model.
  94659. */
  94660. set: function (speed) {
  94661. this._idleRotationSpeed = speed;
  94662. },
  94663. enumerable: true,
  94664. configurable: true
  94665. });
  94666. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94667. /**
  94668. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94669. */
  94670. get: function () {
  94671. return this._idleRotationWaitTime;
  94672. },
  94673. /**
  94674. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94675. */
  94676. set: function (time) {
  94677. this._idleRotationWaitTime = time;
  94678. },
  94679. enumerable: true,
  94680. configurable: true
  94681. });
  94682. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94683. /**
  94684. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94685. */
  94686. get: function () {
  94687. return this._idleRotationSpinupTime;
  94688. },
  94689. /**
  94690. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94691. */
  94692. set: function (time) {
  94693. this._idleRotationSpinupTime = time;
  94694. },
  94695. enumerable: true,
  94696. configurable: true
  94697. });
  94698. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94699. /**
  94700. * Gets a value indicating if the camera is currently rotating because of this behavior
  94701. */
  94702. get: function () {
  94703. return Math.abs(this._cameraRotationSpeed) > 0;
  94704. },
  94705. enumerable: true,
  94706. configurable: true
  94707. });
  94708. AutoRotationBehavior.prototype.init = function () {
  94709. // Do notihng
  94710. };
  94711. AutoRotationBehavior.prototype.attach = function (camera) {
  94712. var _this = this;
  94713. this._attachedCamera = camera;
  94714. var scene = this._attachedCamera.getScene();
  94715. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94716. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94717. _this._isPointerDown = true;
  94718. return;
  94719. }
  94720. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94721. _this._isPointerDown = false;
  94722. }
  94723. });
  94724. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94725. var now = BABYLON.Tools.Now;
  94726. var dt = 0;
  94727. if (_this._lastFrameTime != null) {
  94728. dt = now - _this._lastFrameTime;
  94729. }
  94730. _this._lastFrameTime = now;
  94731. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94732. _this._applyUserInteraction();
  94733. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94734. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94735. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94736. // Step camera rotation by rotation speed
  94737. if (_this._attachedCamera) {
  94738. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94739. }
  94740. });
  94741. };
  94742. AutoRotationBehavior.prototype.detach = function () {
  94743. if (!this._attachedCamera) {
  94744. return;
  94745. }
  94746. var scene = this._attachedCamera.getScene();
  94747. if (this._onPrePointerObservableObserver) {
  94748. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94749. }
  94750. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94751. this._attachedCamera = null;
  94752. };
  94753. /**
  94754. * Returns true if user is scrolling.
  94755. * @return true if user is scrolling.
  94756. */
  94757. AutoRotationBehavior.prototype._userIsZooming = function () {
  94758. if (!this._attachedCamera) {
  94759. return false;
  94760. }
  94761. return this._attachedCamera.inertialRadiusOffset !== 0;
  94762. };
  94763. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94764. if (!this._attachedCamera) {
  94765. return false;
  94766. }
  94767. var zoomHasHitLimit = false;
  94768. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94769. zoomHasHitLimit = true;
  94770. }
  94771. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94772. this._lastFrameRadius = this._attachedCamera.radius;
  94773. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94774. };
  94775. /**
  94776. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94777. */
  94778. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94779. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94780. this._lastInteractionTime = BABYLON.Tools.Now;
  94781. }
  94782. };
  94783. // Tools
  94784. AutoRotationBehavior.prototype._userIsMoving = function () {
  94785. if (!this._attachedCamera) {
  94786. return false;
  94787. }
  94788. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94789. this._attachedCamera.inertialBetaOffset !== 0 ||
  94790. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94791. this._attachedCamera.inertialPanningX !== 0 ||
  94792. this._attachedCamera.inertialPanningY !== 0 ||
  94793. this._isPointerDown;
  94794. };
  94795. return AutoRotationBehavior;
  94796. }());
  94797. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94798. })(BABYLON || (BABYLON = {}));
  94799. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94800. var BABYLON;
  94801. (function (BABYLON) {
  94802. var NullEngineOptions = /** @class */ (function () {
  94803. function NullEngineOptions() {
  94804. this.renderWidth = 512;
  94805. this.renderHeight = 256;
  94806. this.textureSize = 512;
  94807. this.deterministicLockstep = false;
  94808. this.lockstepMaxSteps = 4;
  94809. }
  94810. return NullEngineOptions;
  94811. }());
  94812. BABYLON.NullEngineOptions = NullEngineOptions;
  94813. /**
  94814. * The null engine class provides support for headless version of babylon.js.
  94815. * This can be used in server side scenario or for testing purposes
  94816. */
  94817. var NullEngine = /** @class */ (function (_super) {
  94818. __extends(NullEngine, _super);
  94819. function NullEngine(options) {
  94820. if (options === void 0) { options = new NullEngineOptions(); }
  94821. var _this = _super.call(this, null) || this;
  94822. if (options.deterministicLockstep === undefined) {
  94823. options.deterministicLockstep = false;
  94824. }
  94825. if (options.lockstepMaxSteps === undefined) {
  94826. options.lockstepMaxSteps = 4;
  94827. }
  94828. _this._options = options;
  94829. // Init caps
  94830. // We consider we are on a webgl1 capable device
  94831. _this._caps = new BABYLON.EngineCapabilities();
  94832. _this._caps.maxTexturesImageUnits = 16;
  94833. _this._caps.maxVertexTextureImageUnits = 16;
  94834. _this._caps.maxTextureSize = 512;
  94835. _this._caps.maxCubemapTextureSize = 512;
  94836. _this._caps.maxRenderTextureSize = 512;
  94837. _this._caps.maxVertexAttribs = 16;
  94838. _this._caps.maxVaryingVectors = 16;
  94839. _this._caps.maxFragmentUniformVectors = 16;
  94840. _this._caps.maxVertexUniformVectors = 16;
  94841. // Extensions
  94842. _this._caps.standardDerivatives = false;
  94843. _this._caps.astc = null;
  94844. _this._caps.s3tc = null;
  94845. _this._caps.pvrtc = null;
  94846. _this._caps.etc1 = null;
  94847. _this._caps.etc2 = null;
  94848. _this._caps.textureAnisotropicFilterExtension = null;
  94849. _this._caps.maxAnisotropy = 0;
  94850. _this._caps.uintIndices = false;
  94851. _this._caps.fragmentDepthSupported = false;
  94852. _this._caps.highPrecisionShaderSupported = true;
  94853. _this._caps.colorBufferFloat = false;
  94854. _this._caps.textureFloat = false;
  94855. _this._caps.textureFloatLinearFiltering = false;
  94856. _this._caps.textureFloatRender = false;
  94857. _this._caps.textureHalfFloat = false;
  94858. _this._caps.textureHalfFloatLinearFiltering = false;
  94859. _this._caps.textureHalfFloatRender = false;
  94860. _this._caps.textureLOD = false;
  94861. _this._caps.drawBuffersExtension = false;
  94862. _this._caps.depthTextureExtension = false;
  94863. _this._caps.vertexArrayObject = false;
  94864. _this._caps.instancedArrays = false;
  94865. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94866. // Wrappers
  94867. if (typeof URL === "undefined") {
  94868. URL = {
  94869. createObjectURL: function () { },
  94870. revokeObjectURL: function () { }
  94871. };
  94872. }
  94873. if (typeof Blob === "undefined") {
  94874. Blob = function () { };
  94875. }
  94876. return _this;
  94877. }
  94878. NullEngine.prototype.isDeterministicLockStep = function () {
  94879. return this._options.deterministicLockstep;
  94880. };
  94881. NullEngine.prototype.getLockstepMaxSteps = function () {
  94882. return this._options.lockstepMaxSteps;
  94883. };
  94884. NullEngine.prototype.getHardwareScalingLevel = function () {
  94885. return 1.0;
  94886. };
  94887. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94888. return {
  94889. capacity: 0,
  94890. references: 1,
  94891. is32Bits: false
  94892. };
  94893. };
  94894. NullEngine.prototype.createIndexBuffer = function (indices) {
  94895. return {
  94896. capacity: 0,
  94897. references: 1,
  94898. is32Bits: false
  94899. };
  94900. };
  94901. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  94902. if (stencil === void 0) { stencil = false; }
  94903. };
  94904. NullEngine.prototype.getRenderWidth = function (useScreen) {
  94905. if (useScreen === void 0) { useScreen = false; }
  94906. if (!useScreen && this._currentRenderTarget) {
  94907. return this._currentRenderTarget.width;
  94908. }
  94909. return this._options.renderWidth;
  94910. };
  94911. NullEngine.prototype.getRenderHeight = function (useScreen) {
  94912. if (useScreen === void 0) { useScreen = false; }
  94913. if (!useScreen && this._currentRenderTarget) {
  94914. return this._currentRenderTarget.height;
  94915. }
  94916. return this._options.renderHeight;
  94917. };
  94918. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  94919. this._cachedViewport = viewport;
  94920. };
  94921. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  94922. return {
  94923. transformFeedback: null,
  94924. __SPECTOR_rebuildProgram: null
  94925. };
  94926. };
  94927. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  94928. return [];
  94929. };
  94930. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  94931. return [];
  94932. };
  94933. NullEngine.prototype.bindSamplers = function (effect) {
  94934. this._currentEffect = null;
  94935. };
  94936. NullEngine.prototype.enableEffect = function (effect) {
  94937. this._currentEffect = effect;
  94938. if (effect.onBind) {
  94939. effect.onBind(effect);
  94940. }
  94941. effect.onBindObservable.notifyObservers(effect);
  94942. };
  94943. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  94944. if (zOffset === void 0) { zOffset = 0; }
  94945. if (reverseSide === void 0) { reverseSide = false; }
  94946. };
  94947. NullEngine.prototype.setIntArray = function (uniform, array) {
  94948. };
  94949. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  94950. };
  94951. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  94952. };
  94953. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  94954. };
  94955. NullEngine.prototype.setFloatArray = function (uniform, array) {
  94956. };
  94957. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  94958. };
  94959. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  94960. };
  94961. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  94962. };
  94963. NullEngine.prototype.setArray = function (uniform, array) {
  94964. };
  94965. NullEngine.prototype.setArray2 = function (uniform, array) {
  94966. };
  94967. NullEngine.prototype.setArray3 = function (uniform, array) {
  94968. };
  94969. NullEngine.prototype.setArray4 = function (uniform, array) {
  94970. };
  94971. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  94972. };
  94973. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  94974. };
  94975. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  94976. };
  94977. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  94978. };
  94979. NullEngine.prototype.setFloat = function (uniform, value) {
  94980. };
  94981. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  94982. };
  94983. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  94984. };
  94985. NullEngine.prototype.setBool = function (uniform, bool) {
  94986. };
  94987. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  94988. };
  94989. NullEngine.prototype.setColor3 = function (uniform, color3) {
  94990. };
  94991. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  94992. };
  94993. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  94994. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  94995. if (this._alphaMode === mode) {
  94996. return;
  94997. }
  94998. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  94999. if (!noDepthWriteChange) {
  95000. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95001. }
  95002. this._alphaMode = mode;
  95003. };
  95004. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95005. };
  95006. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95007. if (this.preventCacheWipeBetweenFrames) {
  95008. return;
  95009. }
  95010. this.resetTextureCache();
  95011. this._currentEffect = null;
  95012. if (bruteForce) {
  95013. this._currentProgram = null;
  95014. this._stencilState.reset();
  95015. this._depthCullingState.reset();
  95016. this._alphaState.reset();
  95017. }
  95018. this._cachedVertexBuffers = null;
  95019. this._cachedIndexBuffer = null;
  95020. this._cachedEffectForVertexBuffers = null;
  95021. };
  95022. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95023. };
  95024. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95025. };
  95026. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95027. };
  95028. NullEngine.prototype._createTexture = function () {
  95029. return {};
  95030. };
  95031. NullEngine.prototype._releaseTexture = function (texture) {
  95032. };
  95033. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95034. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95035. if (onLoad === void 0) { onLoad = null; }
  95036. if (onError === void 0) { onError = null; }
  95037. if (buffer === void 0) { buffer = null; }
  95038. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95039. var url = String(urlArg);
  95040. texture.url = url;
  95041. texture.generateMipMaps = !noMipmap;
  95042. texture.samplingMode = samplingMode;
  95043. texture.invertY = invertY;
  95044. texture.baseWidth = this._options.textureSize;
  95045. texture.baseHeight = this._options.textureSize;
  95046. texture.width = this._options.textureSize;
  95047. texture.height = this._options.textureSize;
  95048. if (format) {
  95049. texture.format = format;
  95050. }
  95051. texture.isReady = true;
  95052. if (onLoad) {
  95053. onLoad();
  95054. }
  95055. return texture;
  95056. };
  95057. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95058. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95059. if (options !== undefined && typeof options === "object") {
  95060. fullOptions.generateMipMaps = options.generateMipMaps;
  95061. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95062. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95063. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95064. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95065. }
  95066. else {
  95067. fullOptions.generateMipMaps = options;
  95068. fullOptions.generateDepthBuffer = true;
  95069. fullOptions.generateStencilBuffer = false;
  95070. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95071. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95072. }
  95073. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95074. var width = size.width || size;
  95075. var height = size.height || size;
  95076. texture._depthStencilBuffer = {};
  95077. texture._framebuffer = {};
  95078. texture.baseWidth = width;
  95079. texture.baseHeight = height;
  95080. texture.width = width;
  95081. texture.height = height;
  95082. texture.isReady = true;
  95083. texture.samples = 1;
  95084. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95085. texture.samplingMode = fullOptions.samplingMode;
  95086. texture.type = fullOptions.type;
  95087. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95088. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95089. return texture;
  95090. };
  95091. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95092. texture.samplingMode = samplingMode;
  95093. };
  95094. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95095. if (this._currentRenderTarget) {
  95096. this.unBindFramebuffer(this._currentRenderTarget);
  95097. }
  95098. this._currentRenderTarget = texture;
  95099. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95100. if (this._cachedViewport && !forceFullscreenViewport) {
  95101. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95102. }
  95103. };
  95104. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95105. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95106. this._currentRenderTarget = null;
  95107. if (onBeforeUnbind) {
  95108. if (texture._MSAAFramebuffer) {
  95109. this._currentFramebuffer = texture._framebuffer;
  95110. }
  95111. onBeforeUnbind();
  95112. }
  95113. this._currentFramebuffer = null;
  95114. };
  95115. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95116. var vbo = {
  95117. capacity: 1,
  95118. references: 1,
  95119. is32Bits: false
  95120. };
  95121. return vbo;
  95122. };
  95123. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95124. if (offset === void 0) { offset = 0; }
  95125. };
  95126. /**
  95127. * Updates a dynamic vertex buffer.
  95128. * @param vertexBuffer the vertex buffer to update
  95129. * @param data the data used to update the vertex buffer
  95130. * @param byteOffset the byte offset of the data (optional)
  95131. * @param byteLength the byte length of the data (optional)
  95132. */
  95133. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95134. };
  95135. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95136. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95137. this._boundTexturesCache[this._activeChannel] = texture;
  95138. }
  95139. };
  95140. NullEngine.prototype._bindTexture = function (channel, texture) {
  95141. if (channel < 0) {
  95142. return;
  95143. }
  95144. this._bindTextureDirectly(0, texture);
  95145. };
  95146. NullEngine.prototype._releaseBuffer = function (buffer) {
  95147. buffer.references--;
  95148. if (buffer.references === 0) {
  95149. return true;
  95150. }
  95151. return false;
  95152. };
  95153. NullEngine.prototype.releaseEffects = function () {
  95154. };
  95155. return NullEngine;
  95156. }(BABYLON.Engine));
  95157. BABYLON.NullEngine = NullEngine;
  95158. })(BABYLON || (BABYLON = {}));
  95159. //# sourceMappingURL=babylon.nullEngine.js.map
  95160. var BABYLON;
  95161. (function (BABYLON) {
  95162. /**
  95163. * This class can be used to get instrumentation data from a Babylon engine
  95164. */
  95165. var EngineInstrumentation = /** @class */ (function () {
  95166. function EngineInstrumentation(engine) {
  95167. this.engine = engine;
  95168. this._captureGPUFrameTime = false;
  95169. this._gpuFrameTime = new BABYLON.PerfCounter();
  95170. this._captureShaderCompilationTime = false;
  95171. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95172. // Observers
  95173. this._onBeginFrameObserver = null;
  95174. this._onEndFrameObserver = null;
  95175. this._onBeforeShaderCompilationObserver = null;
  95176. this._onAfterShaderCompilationObserver = null;
  95177. }
  95178. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95179. // Properties
  95180. /**
  95181. * Gets the perf counter used for GPU frame time
  95182. */
  95183. get: function () {
  95184. return this._gpuFrameTime;
  95185. },
  95186. enumerable: true,
  95187. configurable: true
  95188. });
  95189. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95190. /**
  95191. * Gets the GPU frame time capture status
  95192. */
  95193. get: function () {
  95194. return this._captureGPUFrameTime;
  95195. },
  95196. /**
  95197. * Enable or disable the GPU frame time capture
  95198. */
  95199. set: function (value) {
  95200. var _this = this;
  95201. if (value === this._captureGPUFrameTime) {
  95202. return;
  95203. }
  95204. this._captureGPUFrameTime = value;
  95205. if (value) {
  95206. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95207. if (!_this._gpuFrameTimeToken) {
  95208. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95209. }
  95210. });
  95211. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95212. if (!_this._gpuFrameTimeToken) {
  95213. return;
  95214. }
  95215. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95216. if (time > -1) {
  95217. _this._gpuFrameTimeToken = null;
  95218. _this._gpuFrameTime.fetchNewFrame();
  95219. _this._gpuFrameTime.addCount(time, true);
  95220. }
  95221. });
  95222. }
  95223. else {
  95224. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95225. this._onBeginFrameObserver = null;
  95226. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95227. this._onEndFrameObserver = null;
  95228. }
  95229. },
  95230. enumerable: true,
  95231. configurable: true
  95232. });
  95233. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95234. /**
  95235. * Gets the perf counter used for shader compilation time
  95236. */
  95237. get: function () {
  95238. return this._shaderCompilationTime;
  95239. },
  95240. enumerable: true,
  95241. configurable: true
  95242. });
  95243. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95244. /**
  95245. * Gets the shader compilation time capture status
  95246. */
  95247. get: function () {
  95248. return this._captureShaderCompilationTime;
  95249. },
  95250. /**
  95251. * Enable or disable the shader compilation time capture
  95252. */
  95253. set: function (value) {
  95254. var _this = this;
  95255. if (value === this._captureShaderCompilationTime) {
  95256. return;
  95257. }
  95258. this._captureShaderCompilationTime = value;
  95259. if (value) {
  95260. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95261. _this._shaderCompilationTime.fetchNewFrame();
  95262. _this._shaderCompilationTime.beginMonitoring();
  95263. });
  95264. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95265. _this._shaderCompilationTime.endMonitoring();
  95266. });
  95267. }
  95268. else {
  95269. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95270. this._onBeforeShaderCompilationObserver = null;
  95271. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95272. this._onAfterShaderCompilationObserver = null;
  95273. }
  95274. },
  95275. enumerable: true,
  95276. configurable: true
  95277. });
  95278. EngineInstrumentation.prototype.dispose = function () {
  95279. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95280. this._onBeginFrameObserver = null;
  95281. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95282. this._onEndFrameObserver = null;
  95283. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95284. this._onBeforeShaderCompilationObserver = null;
  95285. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95286. this._onAfterShaderCompilationObserver = null;
  95287. this.engine = null;
  95288. };
  95289. return EngineInstrumentation;
  95290. }());
  95291. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95292. })(BABYLON || (BABYLON = {}));
  95293. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95294. var BABYLON;
  95295. (function (BABYLON) {
  95296. /**
  95297. * This class can be used to get instrumentation data from a Babylon engine
  95298. */
  95299. var SceneInstrumentation = /** @class */ (function () {
  95300. function SceneInstrumentation(scene) {
  95301. var _this = this;
  95302. this.scene = scene;
  95303. this._captureActiveMeshesEvaluationTime = false;
  95304. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95305. this._captureRenderTargetsRenderTime = false;
  95306. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95307. this._captureFrameTime = false;
  95308. this._frameTime = new BABYLON.PerfCounter();
  95309. this._captureRenderTime = false;
  95310. this._renderTime = new BABYLON.PerfCounter();
  95311. this._captureInterFrameTime = false;
  95312. this._interFrameTime = new BABYLON.PerfCounter();
  95313. this._captureParticlesRenderTime = false;
  95314. this._particlesRenderTime = new BABYLON.PerfCounter();
  95315. this._captureSpritesRenderTime = false;
  95316. this._spritesRenderTime = new BABYLON.PerfCounter();
  95317. this._capturePhysicsTime = false;
  95318. this._physicsTime = new BABYLON.PerfCounter();
  95319. this._captureAnimationsTime = false;
  95320. this._animationsTime = new BABYLON.PerfCounter();
  95321. // Observers
  95322. this._onBeforeActiveMeshesEvaluationObserver = null;
  95323. this._onAfterActiveMeshesEvaluationObserver = null;
  95324. this._onBeforeRenderTargetsRenderObserver = null;
  95325. this._onAfterRenderTargetsRenderObserver = null;
  95326. this._onAfterRenderObserver = null;
  95327. this._onBeforeDrawPhaseObserver = null;
  95328. this._onAfterDrawPhaseObserver = null;
  95329. this._onBeforeAnimationsObserver = null;
  95330. this._onBeforeParticlesRenderingObserver = null;
  95331. this._onAfterParticlesRenderingObserver = null;
  95332. this._onBeforeSpritesRenderingObserver = null;
  95333. this._onAfterSpritesRenderingObserver = null;
  95334. this._onBeforePhysicsObserver = null;
  95335. this._onAfterPhysicsObserver = null;
  95336. this._onAfterAnimationsObserver = null;
  95337. // Before render
  95338. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95339. if (_this._captureActiveMeshesEvaluationTime) {
  95340. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95341. }
  95342. if (_this._captureRenderTargetsRenderTime) {
  95343. _this._renderTargetsRenderTime.fetchNewFrame();
  95344. }
  95345. if (_this._captureFrameTime) {
  95346. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95347. _this._frameTime.beginMonitoring();
  95348. }
  95349. if (_this._captureInterFrameTime) {
  95350. _this._interFrameTime.endMonitoring();
  95351. }
  95352. if (_this._captureParticlesRenderTime) {
  95353. _this._particlesRenderTime.fetchNewFrame();
  95354. }
  95355. if (_this._captureSpritesRenderTime) {
  95356. _this._spritesRenderTime.fetchNewFrame();
  95357. }
  95358. if (_this._captureAnimationsTime) {
  95359. _this._animationsTime.beginMonitoring();
  95360. }
  95361. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95362. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95363. });
  95364. // After render
  95365. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95366. if (_this._captureFrameTime) {
  95367. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95368. _this._frameTime.endMonitoring();
  95369. }
  95370. if (_this._captureRenderTime) {
  95371. _this._renderTime.endMonitoring(false);
  95372. }
  95373. if (_this._captureInterFrameTime) {
  95374. _this._interFrameTime.beginMonitoring();
  95375. }
  95376. });
  95377. }
  95378. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95379. // Properties
  95380. /**
  95381. * Gets the perf counter used for active meshes evaluation time
  95382. */
  95383. get: function () {
  95384. return this._activeMeshesEvaluationTime;
  95385. },
  95386. enumerable: true,
  95387. configurable: true
  95388. });
  95389. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95390. /**
  95391. * Gets the active meshes evaluation time capture status
  95392. */
  95393. get: function () {
  95394. return this._captureActiveMeshesEvaluationTime;
  95395. },
  95396. /**
  95397. * Enable or disable the active meshes evaluation time capture
  95398. */
  95399. set: function (value) {
  95400. var _this = this;
  95401. if (value === this._captureActiveMeshesEvaluationTime) {
  95402. return;
  95403. }
  95404. this._captureActiveMeshesEvaluationTime = value;
  95405. if (value) {
  95406. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95407. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95408. _this._activeMeshesEvaluationTime.beginMonitoring();
  95409. });
  95410. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95411. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95412. _this._activeMeshesEvaluationTime.endMonitoring();
  95413. });
  95414. }
  95415. else {
  95416. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95417. this._onBeforeActiveMeshesEvaluationObserver = null;
  95418. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95419. this._onAfterActiveMeshesEvaluationObserver = null;
  95420. }
  95421. },
  95422. enumerable: true,
  95423. configurable: true
  95424. });
  95425. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95426. /**
  95427. * Gets the perf counter used for render targets render time
  95428. */
  95429. get: function () {
  95430. return this._renderTargetsRenderTime;
  95431. },
  95432. enumerable: true,
  95433. configurable: true
  95434. });
  95435. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95436. /**
  95437. * Gets the render targets render time capture status
  95438. */
  95439. get: function () {
  95440. return this._captureRenderTargetsRenderTime;
  95441. },
  95442. /**
  95443. * Enable or disable the render targets render time capture
  95444. */
  95445. set: function (value) {
  95446. var _this = this;
  95447. if (value === this._captureRenderTargetsRenderTime) {
  95448. return;
  95449. }
  95450. this._captureRenderTargetsRenderTime = value;
  95451. if (value) {
  95452. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95453. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95454. _this._renderTargetsRenderTime.beginMonitoring();
  95455. });
  95456. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95457. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95458. _this._renderTargetsRenderTime.endMonitoring(false);
  95459. });
  95460. }
  95461. else {
  95462. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95463. this._onBeforeRenderTargetsRenderObserver = null;
  95464. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95465. this._onAfterRenderTargetsRenderObserver = null;
  95466. }
  95467. },
  95468. enumerable: true,
  95469. configurable: true
  95470. });
  95471. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95472. /**
  95473. * Gets the perf counter used for particles render time
  95474. */
  95475. get: function () {
  95476. return this._particlesRenderTime;
  95477. },
  95478. enumerable: true,
  95479. configurable: true
  95480. });
  95481. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95482. /**
  95483. * Gets the particles render time capture status
  95484. */
  95485. get: function () {
  95486. return this._captureParticlesRenderTime;
  95487. },
  95488. /**
  95489. * Enable or disable the particles render time capture
  95490. */
  95491. set: function (value) {
  95492. var _this = this;
  95493. if (value === this._captureParticlesRenderTime) {
  95494. return;
  95495. }
  95496. this._captureParticlesRenderTime = value;
  95497. if (value) {
  95498. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95499. BABYLON.Tools.StartPerformanceCounter("Particles");
  95500. _this._particlesRenderTime.beginMonitoring();
  95501. });
  95502. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95503. BABYLON.Tools.EndPerformanceCounter("Particles");
  95504. _this._particlesRenderTime.endMonitoring(false);
  95505. });
  95506. }
  95507. else {
  95508. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95509. this._onBeforeParticlesRenderingObserver = null;
  95510. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95511. this._onAfterParticlesRenderingObserver = null;
  95512. }
  95513. },
  95514. enumerable: true,
  95515. configurable: true
  95516. });
  95517. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95518. /**
  95519. * Gets the perf counter used for sprites render time
  95520. */
  95521. get: function () {
  95522. return this._spritesRenderTime;
  95523. },
  95524. enumerable: true,
  95525. configurable: true
  95526. });
  95527. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95528. /**
  95529. * Gets the sprites render time capture status
  95530. */
  95531. get: function () {
  95532. return this._captureSpritesRenderTime;
  95533. },
  95534. /**
  95535. * Enable or disable the sprites render time capture
  95536. */
  95537. set: function (value) {
  95538. var _this = this;
  95539. if (value === this._captureSpritesRenderTime) {
  95540. return;
  95541. }
  95542. this._captureSpritesRenderTime = value;
  95543. if (value) {
  95544. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95545. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95546. _this._spritesRenderTime.beginMonitoring();
  95547. });
  95548. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95549. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95550. _this._spritesRenderTime.endMonitoring(false);
  95551. });
  95552. }
  95553. else {
  95554. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95555. this._onBeforeSpritesRenderingObserver = null;
  95556. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95557. this._onAfterSpritesRenderingObserver = null;
  95558. }
  95559. },
  95560. enumerable: true,
  95561. configurable: true
  95562. });
  95563. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95564. /**
  95565. * Gets the perf counter used for physics time
  95566. */
  95567. get: function () {
  95568. return this._physicsTime;
  95569. },
  95570. enumerable: true,
  95571. configurable: true
  95572. });
  95573. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95574. /**
  95575. * Gets the physics time capture status
  95576. */
  95577. get: function () {
  95578. return this._capturePhysicsTime;
  95579. },
  95580. /**
  95581. * Enable or disable the physics time capture
  95582. */
  95583. set: function (value) {
  95584. var _this = this;
  95585. if (value === this._capturePhysicsTime) {
  95586. return;
  95587. }
  95588. this._capturePhysicsTime = value;
  95589. if (value) {
  95590. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95591. BABYLON.Tools.StartPerformanceCounter("Physics");
  95592. _this._physicsTime.beginMonitoring();
  95593. });
  95594. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95595. BABYLON.Tools.EndPerformanceCounter("Physics");
  95596. _this._physicsTime.endMonitoring();
  95597. });
  95598. }
  95599. else {
  95600. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95601. this._onBeforePhysicsObserver = null;
  95602. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95603. this._onAfterPhysicsObserver = null;
  95604. }
  95605. },
  95606. enumerable: true,
  95607. configurable: true
  95608. });
  95609. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95610. /**
  95611. * Gets the perf counter used for animations time
  95612. */
  95613. get: function () {
  95614. return this._animationsTime;
  95615. },
  95616. enumerable: true,
  95617. configurable: true
  95618. });
  95619. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95620. /**
  95621. * Gets the animations time capture status
  95622. */
  95623. get: function () {
  95624. return this._captureAnimationsTime;
  95625. },
  95626. /**
  95627. * Enable or disable the animations time capture
  95628. */
  95629. set: function (value) {
  95630. var _this = this;
  95631. if (value === this._captureAnimationsTime) {
  95632. return;
  95633. }
  95634. this._captureAnimationsTime = value;
  95635. if (value) {
  95636. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95637. _this._animationsTime.endMonitoring();
  95638. });
  95639. }
  95640. else {
  95641. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95642. this._onAfterAnimationsObserver = null;
  95643. }
  95644. },
  95645. enumerable: true,
  95646. configurable: true
  95647. });
  95648. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95649. /**
  95650. * Gets the perf counter used for frame time capture
  95651. */
  95652. get: function () {
  95653. return this._frameTime;
  95654. },
  95655. enumerable: true,
  95656. configurable: true
  95657. });
  95658. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95659. /**
  95660. * Gets the frame time capture status
  95661. */
  95662. get: function () {
  95663. return this._captureFrameTime;
  95664. },
  95665. /**
  95666. * Enable or disable the frame time capture
  95667. */
  95668. set: function (value) {
  95669. this._captureFrameTime = value;
  95670. },
  95671. enumerable: true,
  95672. configurable: true
  95673. });
  95674. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95675. /**
  95676. * Gets the perf counter used for inter-frames time capture
  95677. */
  95678. get: function () {
  95679. return this._interFrameTime;
  95680. },
  95681. enumerable: true,
  95682. configurable: true
  95683. });
  95684. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95685. /**
  95686. * Gets the inter-frames time capture status
  95687. */
  95688. get: function () {
  95689. return this._captureInterFrameTime;
  95690. },
  95691. /**
  95692. * Enable or disable the inter-frames time capture
  95693. */
  95694. set: function (value) {
  95695. this._captureInterFrameTime = value;
  95696. },
  95697. enumerable: true,
  95698. configurable: true
  95699. });
  95700. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95701. /**
  95702. * Gets the perf counter used for render time capture
  95703. */
  95704. get: function () {
  95705. return this._renderTime;
  95706. },
  95707. enumerable: true,
  95708. configurable: true
  95709. });
  95710. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95711. /**
  95712. * Gets the render time capture status
  95713. */
  95714. get: function () {
  95715. return this._captureRenderTime;
  95716. },
  95717. /**
  95718. * Enable or disable the render time capture
  95719. */
  95720. set: function (value) {
  95721. var _this = this;
  95722. if (value === this._captureRenderTime) {
  95723. return;
  95724. }
  95725. this._captureRenderTime = value;
  95726. if (value) {
  95727. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95728. _this._renderTime.beginMonitoring();
  95729. BABYLON.Tools.StartPerformanceCounter("Main render");
  95730. });
  95731. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95732. _this._renderTime.endMonitoring(false);
  95733. BABYLON.Tools.EndPerformanceCounter("Main render");
  95734. });
  95735. }
  95736. else {
  95737. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95738. this._onBeforeDrawPhaseObserver = null;
  95739. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95740. this._onAfterDrawPhaseObserver = null;
  95741. }
  95742. },
  95743. enumerable: true,
  95744. configurable: true
  95745. });
  95746. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95747. /**
  95748. * Gets the perf counter used for draw calls
  95749. */
  95750. get: function () {
  95751. return this.scene.getEngine()._drawCalls;
  95752. },
  95753. enumerable: true,
  95754. configurable: true
  95755. });
  95756. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95757. /**
  95758. * Gets the perf counter used for texture collisions
  95759. */
  95760. get: function () {
  95761. return this.scene.getEngine()._textureCollisions;
  95762. },
  95763. enumerable: true,
  95764. configurable: true
  95765. });
  95766. SceneInstrumentation.prototype.dispose = function () {
  95767. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95768. this._onAfterRenderObserver = null;
  95769. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95770. this._onBeforeActiveMeshesEvaluationObserver = null;
  95771. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95772. this._onAfterActiveMeshesEvaluationObserver = null;
  95773. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95774. this._onBeforeRenderTargetsRenderObserver = null;
  95775. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95776. this._onAfterRenderTargetsRenderObserver = null;
  95777. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95778. this._onBeforeAnimationsObserver = null;
  95779. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95780. this._onBeforeParticlesRenderingObserver = null;
  95781. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95782. this._onAfterParticlesRenderingObserver = null;
  95783. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95784. this._onBeforeSpritesRenderingObserver = null;
  95785. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95786. this._onAfterSpritesRenderingObserver = null;
  95787. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95788. this._onBeforeDrawPhaseObserver = null;
  95789. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95790. this._onAfterDrawPhaseObserver = null;
  95791. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95792. this._onBeforePhysicsObserver = null;
  95793. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95794. this._onAfterPhysicsObserver = null;
  95795. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95796. this._onAfterAnimationsObserver = null;
  95797. this.scene = null;
  95798. };
  95799. return SceneInstrumentation;
  95800. }());
  95801. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95802. })(BABYLON || (BABYLON = {}));
  95803. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95804. var BABYLON;
  95805. (function (BABYLON) {
  95806. /**
  95807. * @hidden
  95808. **/
  95809. var _TimeToken = /** @class */ (function () {
  95810. function _TimeToken() {
  95811. this._timeElapsedQueryEnded = false;
  95812. }
  95813. return _TimeToken;
  95814. }());
  95815. BABYLON._TimeToken = _TimeToken;
  95816. })(BABYLON || (BABYLON = {}));
  95817. //# sourceMappingURL=babylon.timeToken.js.map
  95818. var BABYLON;
  95819. (function (BABYLON) {
  95820. /**
  95821. * Background material defines definition.
  95822. * @hidden Mainly internal Use
  95823. */
  95824. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95825. __extends(BackgroundMaterialDefines, _super);
  95826. /**
  95827. * Constructor of the defines.
  95828. */
  95829. function BackgroundMaterialDefines() {
  95830. var _this = _super.call(this) || this;
  95831. /**
  95832. * True if the diffuse texture is in use.
  95833. */
  95834. _this.DIFFUSE = false;
  95835. /**
  95836. * The direct UV channel to use.
  95837. */
  95838. _this.DIFFUSEDIRECTUV = 0;
  95839. /**
  95840. * True if the diffuse texture is in gamma space.
  95841. */
  95842. _this.GAMMADIFFUSE = false;
  95843. /**
  95844. * True if the diffuse texture has opacity in the alpha channel.
  95845. */
  95846. _this.DIFFUSEHASALPHA = false;
  95847. /**
  95848. * True if you want the material to fade to transparent at grazing angle.
  95849. */
  95850. _this.OPACITYFRESNEL = false;
  95851. /**
  95852. * True if an extra blur needs to be added in the reflection.
  95853. */
  95854. _this.REFLECTIONBLUR = false;
  95855. /**
  95856. * True if you want the material to fade to reflection at grazing angle.
  95857. */
  95858. _this.REFLECTIONFRESNEL = false;
  95859. /**
  95860. * True if you want the material to falloff as far as you move away from the scene center.
  95861. */
  95862. _this.REFLECTIONFALLOFF = false;
  95863. /**
  95864. * False if the current Webgl implementation does not support the texture lod extension.
  95865. */
  95866. _this.TEXTURELODSUPPORT = false;
  95867. /**
  95868. * True to ensure the data are premultiplied.
  95869. */
  95870. _this.PREMULTIPLYALPHA = false;
  95871. /**
  95872. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95873. */
  95874. _this.USERGBCOLOR = false;
  95875. /**
  95876. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95877. * stays aligned with the desired configuration.
  95878. */
  95879. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95880. /**
  95881. * True to add noise in order to reduce the banding effect.
  95882. */
  95883. _this.NOISE = false;
  95884. /**
  95885. * is the reflection texture in BGR color scheme?
  95886. * Mainly used to solve a bug in ios10 video tag
  95887. */
  95888. _this.REFLECTIONBGR = false;
  95889. _this.IMAGEPROCESSING = false;
  95890. _this.VIGNETTE = false;
  95891. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95892. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95893. _this.TONEMAPPING = false;
  95894. _this.CONTRAST = false;
  95895. _this.COLORCURVES = false;
  95896. _this.COLORGRADING = false;
  95897. _this.COLORGRADING3D = false;
  95898. _this.SAMPLER3DGREENDEPTH = false;
  95899. _this.SAMPLER3DBGRMAP = false;
  95900. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95901. _this.EXPOSURE = false;
  95902. // Reflection.
  95903. _this.REFLECTION = false;
  95904. _this.REFLECTIONMAP_3D = false;
  95905. _this.REFLECTIONMAP_SPHERICAL = false;
  95906. _this.REFLECTIONMAP_PLANAR = false;
  95907. _this.REFLECTIONMAP_CUBIC = false;
  95908. _this.REFLECTIONMAP_PROJECTION = false;
  95909. _this.REFLECTIONMAP_SKYBOX = false;
  95910. _this.REFLECTIONMAP_EXPLICIT = false;
  95911. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95912. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95913. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95914. _this.INVERTCUBICMAP = false;
  95915. _this.REFLECTIONMAP_OPPOSITEZ = false;
  95916. _this.LODINREFLECTIONALPHA = false;
  95917. _this.GAMMAREFLECTION = false;
  95918. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  95919. // Default BJS.
  95920. _this.MAINUV1 = false;
  95921. _this.MAINUV2 = false;
  95922. _this.UV1 = false;
  95923. _this.UV2 = false;
  95924. _this.CLIPPLANE = false;
  95925. _this.POINTSIZE = false;
  95926. _this.FOG = false;
  95927. _this.NORMAL = false;
  95928. _this.NUM_BONE_INFLUENCERS = 0;
  95929. _this.BonesPerMesh = 0;
  95930. _this.INSTANCES = false;
  95931. _this.SHADOWFLOAT = false;
  95932. _this.rebuild();
  95933. return _this;
  95934. }
  95935. return BackgroundMaterialDefines;
  95936. }(BABYLON.MaterialDefines));
  95937. /**
  95938. * Background material used to create an efficient environement around your scene.
  95939. */
  95940. var BackgroundMaterial = /** @class */ (function (_super) {
  95941. __extends(BackgroundMaterial, _super);
  95942. /**
  95943. * Instantiates a Background Material in the given scene
  95944. * @param name The friendly name of the material
  95945. * @param scene The scene to add the material to
  95946. */
  95947. function BackgroundMaterial(name, scene) {
  95948. var _this = _super.call(this, name, scene) || this;
  95949. /**
  95950. * Key light Color (multiply against the environement texture)
  95951. */
  95952. _this.primaryColor = BABYLON.Color3.White();
  95953. _this._primaryColorShadowLevel = 0;
  95954. _this._primaryColorHighlightLevel = 0;
  95955. /**
  95956. * Reflection Texture used in the material.
  95957. * Should be author in a specific way for the best result (refer to the documentation).
  95958. */
  95959. _this.reflectionTexture = null;
  95960. /**
  95961. * Reflection Texture level of blur.
  95962. *
  95963. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  95964. * texture twice.
  95965. */
  95966. _this.reflectionBlur = 0;
  95967. /**
  95968. * Diffuse Texture used in the material.
  95969. * Should be author in a specific way for the best result (refer to the documentation).
  95970. */
  95971. _this.diffuseTexture = null;
  95972. _this._shadowLights = null;
  95973. /**
  95974. * Specify the list of lights casting shadow on the material.
  95975. * All scene shadow lights will be included if null.
  95976. */
  95977. _this.shadowLights = null;
  95978. /**
  95979. * Helps adjusting the shadow to a softer level if required.
  95980. * 0 means black shadows and 1 means no shadows.
  95981. */
  95982. _this.shadowLevel = 0;
  95983. /**
  95984. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  95985. * It is usually zero but might be interesting to modify according to your setup.
  95986. */
  95987. _this.sceneCenter = BABYLON.Vector3.Zero();
  95988. /**
  95989. * This helps specifying that the material is falling off to the sky box at grazing angle.
  95990. * This helps ensuring a nice transition when the camera goes under the ground.
  95991. */
  95992. _this.opacityFresnel = true;
  95993. /**
  95994. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  95995. * This helps adding a mirror texture on the ground.
  95996. */
  95997. _this.reflectionFresnel = false;
  95998. /**
  95999. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96000. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96001. */
  96002. _this.reflectionFalloffDistance = 0.0;
  96003. /**
  96004. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96005. */
  96006. _this.reflectionAmount = 1.0;
  96007. /**
  96008. * This specifies the weight of the reflection at grazing angle.
  96009. */
  96010. _this.reflectionReflectance0 = 0.05;
  96011. /**
  96012. * This specifies the weight of the reflection at a perpendicular point of view.
  96013. */
  96014. _this.reflectionReflectance90 = 0.5;
  96015. /**
  96016. * Helps to directly use the maps channels instead of their level.
  96017. */
  96018. _this.useRGBColor = true;
  96019. /**
  96020. * This helps reducing the banding effect that could occur on the background.
  96021. */
  96022. _this.enableNoise = false;
  96023. _this._fovMultiplier = 1.0;
  96024. /**
  96025. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96026. */
  96027. _this.useEquirectangularFOV = false;
  96028. _this._maxSimultaneousLights = 4;
  96029. /**
  96030. * Number of Simultaneous lights allowed on the material.
  96031. */
  96032. _this.maxSimultaneousLights = 4;
  96033. /**
  96034. * Keep track of the image processing observer to allow dispose and replace.
  96035. */
  96036. _this._imageProcessingObserver = null;
  96037. /**
  96038. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96039. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96040. */
  96041. _this.switchToBGR = false;
  96042. // Temp values kept as cache in the material.
  96043. _this._renderTargets = new BABYLON.SmartArray(16);
  96044. _this._reflectionControls = BABYLON.Vector4.Zero();
  96045. _this._white = BABYLON.Color3.White();
  96046. _this._primaryShadowColor = BABYLON.Color3.Black();
  96047. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96048. // Setup the default processing configuration to the scene.
  96049. _this._attachImageProcessingConfiguration(null);
  96050. _this.getRenderTargetTextures = function () {
  96051. _this._renderTargets.reset();
  96052. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96053. _this._renderTargets.push(_this._diffuseTexture);
  96054. }
  96055. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96056. _this._renderTargets.push(_this._reflectionTexture);
  96057. }
  96058. return _this._renderTargets;
  96059. };
  96060. return _this;
  96061. }
  96062. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96063. /**
  96064. * Experimental Internal Use Only.
  96065. *
  96066. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96067. * This acts as a helper to set the primary color to a more "human friendly" value.
  96068. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96069. * output color as close as possible from the chosen value.
  96070. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96071. * part of lighting setup.)
  96072. */
  96073. get: function () {
  96074. return this.__perceptualColor;
  96075. },
  96076. set: function (value) {
  96077. this.__perceptualColor = value;
  96078. this._computePrimaryColorFromPerceptualColor();
  96079. this._markAllSubMeshesAsLightsDirty();
  96080. },
  96081. enumerable: true,
  96082. configurable: true
  96083. });
  96084. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96085. /**
  96086. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96087. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96088. */
  96089. get: function () {
  96090. return this._primaryColorShadowLevel;
  96091. },
  96092. set: function (value) {
  96093. this._primaryColorShadowLevel = value;
  96094. this._computePrimaryColors();
  96095. this._markAllSubMeshesAsLightsDirty();
  96096. },
  96097. enumerable: true,
  96098. configurable: true
  96099. });
  96100. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96101. /**
  96102. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96103. * The primary color is used at the level chosen to define what the white area would look.
  96104. */
  96105. get: function () {
  96106. return this._primaryColorHighlightLevel;
  96107. },
  96108. set: function (value) {
  96109. this._primaryColorHighlightLevel = value;
  96110. this._computePrimaryColors();
  96111. this._markAllSubMeshesAsLightsDirty();
  96112. },
  96113. enumerable: true,
  96114. configurable: true
  96115. });
  96116. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96117. /**
  96118. * Sets the reflection reflectance fresnel values according to the default standard
  96119. * empirically know to work well :-)
  96120. */
  96121. set: function (value) {
  96122. var reflectionWeight = value;
  96123. if (reflectionWeight < 0.5) {
  96124. reflectionWeight = reflectionWeight * 2.0;
  96125. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96126. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96127. }
  96128. else {
  96129. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96130. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96131. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96132. }
  96133. },
  96134. enumerable: true,
  96135. configurable: true
  96136. });
  96137. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96138. /**
  96139. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96140. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96141. * Recommended to be keep at 1.0 except for special cases.
  96142. */
  96143. get: function () {
  96144. return this._fovMultiplier;
  96145. },
  96146. set: function (value) {
  96147. if (isNaN(value)) {
  96148. value = 1.0;
  96149. }
  96150. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96151. },
  96152. enumerable: true,
  96153. configurable: true
  96154. });
  96155. /**
  96156. * Attaches a new image processing configuration to the PBR Material.
  96157. * @param configuration (if null the scene configuration will be use)
  96158. */
  96159. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96160. var _this = this;
  96161. if (configuration === this._imageProcessingConfiguration) {
  96162. return;
  96163. }
  96164. // Detaches observer.
  96165. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96166. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96167. }
  96168. // Pick the scene configuration if needed.
  96169. if (!configuration) {
  96170. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96171. }
  96172. else {
  96173. this._imageProcessingConfiguration = configuration;
  96174. }
  96175. // Attaches observer.
  96176. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96177. _this._computePrimaryColorFromPerceptualColor();
  96178. _this._markAllSubMeshesAsImageProcessingDirty();
  96179. });
  96180. };
  96181. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96182. /**
  96183. * Gets the image processing configuration used either in this material.
  96184. */
  96185. get: function () {
  96186. return this._imageProcessingConfiguration;
  96187. },
  96188. /**
  96189. * Sets the Default image processing configuration used either in the this material.
  96190. *
  96191. * If sets to null, the scene one is in use.
  96192. */
  96193. set: function (value) {
  96194. this._attachImageProcessingConfiguration(value);
  96195. // Ensure the effect will be rebuilt.
  96196. this._markAllSubMeshesAsTexturesDirty();
  96197. },
  96198. enumerable: true,
  96199. configurable: true
  96200. });
  96201. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96202. /**
  96203. * Gets wether the color curves effect is enabled.
  96204. */
  96205. get: function () {
  96206. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96207. },
  96208. /**
  96209. * Sets wether the color curves effect is enabled.
  96210. */
  96211. set: function (value) {
  96212. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96213. },
  96214. enumerable: true,
  96215. configurable: true
  96216. });
  96217. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96218. /**
  96219. * Gets wether the color grading effect is enabled.
  96220. */
  96221. get: function () {
  96222. return this.imageProcessingConfiguration.colorGradingEnabled;
  96223. },
  96224. /**
  96225. * Gets wether the color grading effect is enabled.
  96226. */
  96227. set: function (value) {
  96228. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96229. },
  96230. enumerable: true,
  96231. configurable: true
  96232. });
  96233. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96234. /**
  96235. * Gets wether tonemapping is enabled or not.
  96236. */
  96237. get: function () {
  96238. return this._imageProcessingConfiguration.toneMappingEnabled;
  96239. },
  96240. /**
  96241. * Sets wether tonemapping is enabled or not
  96242. */
  96243. set: function (value) {
  96244. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96245. },
  96246. enumerable: true,
  96247. configurable: true
  96248. });
  96249. ;
  96250. ;
  96251. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96252. /**
  96253. * The camera exposure used on this material.
  96254. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96255. * This corresponds to a photographic exposure.
  96256. */
  96257. get: function () {
  96258. return this._imageProcessingConfiguration.exposure;
  96259. },
  96260. /**
  96261. * The camera exposure used on this material.
  96262. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96263. * This corresponds to a photographic exposure.
  96264. */
  96265. set: function (value) {
  96266. this._imageProcessingConfiguration.exposure = value;
  96267. },
  96268. enumerable: true,
  96269. configurable: true
  96270. });
  96271. ;
  96272. ;
  96273. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96274. /**
  96275. * Gets The camera contrast used on this material.
  96276. */
  96277. get: function () {
  96278. return this._imageProcessingConfiguration.contrast;
  96279. },
  96280. /**
  96281. * Sets The camera contrast used on this material.
  96282. */
  96283. set: function (value) {
  96284. this._imageProcessingConfiguration.contrast = value;
  96285. },
  96286. enumerable: true,
  96287. configurable: true
  96288. });
  96289. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96290. /**
  96291. * Gets the Color Grading 2D Lookup Texture.
  96292. */
  96293. get: function () {
  96294. return this._imageProcessingConfiguration.colorGradingTexture;
  96295. },
  96296. /**
  96297. * Sets the Color Grading 2D Lookup Texture.
  96298. */
  96299. set: function (value) {
  96300. this.imageProcessingConfiguration.colorGradingTexture = value;
  96301. },
  96302. enumerable: true,
  96303. configurable: true
  96304. });
  96305. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96306. /**
  96307. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96308. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96309. * 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;
  96310. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96311. */
  96312. get: function () {
  96313. return this.imageProcessingConfiguration.colorCurves;
  96314. },
  96315. /**
  96316. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96317. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96318. * 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;
  96319. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96320. */
  96321. set: function (value) {
  96322. this.imageProcessingConfiguration.colorCurves = value;
  96323. },
  96324. enumerable: true,
  96325. configurable: true
  96326. });
  96327. /**
  96328. * The entire material has been created in order to prevent overdraw.
  96329. * @returns false
  96330. */
  96331. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96332. return true;
  96333. };
  96334. /**
  96335. * The entire material has been created in order to prevent overdraw.
  96336. * @returns true if blending is enable
  96337. */
  96338. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96339. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96340. };
  96341. /**
  96342. * Checks wether the material is ready to be rendered for a given mesh.
  96343. * @param mesh The mesh to render
  96344. * @param subMesh The submesh to check against
  96345. * @param useInstances Specify wether or not the material is used with instances
  96346. * @returns true if all the dependencies are ready (Textures, Effects...)
  96347. */
  96348. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96349. var _this = this;
  96350. if (useInstances === void 0) { useInstances = false; }
  96351. if (subMesh.effect && this.isFrozen) {
  96352. if (this._wasPreviouslyReady) {
  96353. return true;
  96354. }
  96355. }
  96356. if (!subMesh._materialDefines) {
  96357. subMesh._materialDefines = new BackgroundMaterialDefines();
  96358. }
  96359. var scene = this.getScene();
  96360. var defines = subMesh._materialDefines;
  96361. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96362. if (defines._renderId === scene.getRenderId()) {
  96363. return true;
  96364. }
  96365. }
  96366. var engine = scene.getEngine();
  96367. // Lights
  96368. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96369. defines._needNormals = true;
  96370. // Textures
  96371. if (defines._areTexturesDirty) {
  96372. defines._needUVs = false;
  96373. if (scene.texturesEnabled) {
  96374. if (scene.getEngine().getCaps().textureLOD) {
  96375. defines.TEXTURELODSUPPORT = true;
  96376. }
  96377. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96378. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96379. return false;
  96380. }
  96381. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96382. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96383. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96384. defines.OPACITYFRESNEL = this._opacityFresnel;
  96385. }
  96386. else {
  96387. defines.DIFFUSE = false;
  96388. defines.DIFFUSEHASALPHA = false;
  96389. defines.GAMMADIFFUSE = false;
  96390. defines.OPACITYFRESNEL = false;
  96391. }
  96392. var reflectionTexture = this._reflectionTexture;
  96393. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96394. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96395. return false;
  96396. }
  96397. defines.REFLECTION = true;
  96398. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96399. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96400. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96401. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96402. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96403. defines.REFLECTIONBGR = this.switchToBGR;
  96404. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96405. defines.INVERTCUBICMAP = true;
  96406. }
  96407. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96408. switch (reflectionTexture.coordinatesMode) {
  96409. case BABYLON.Texture.EXPLICIT_MODE:
  96410. defines.REFLECTIONMAP_EXPLICIT = true;
  96411. break;
  96412. case BABYLON.Texture.PLANAR_MODE:
  96413. defines.REFLECTIONMAP_PLANAR = true;
  96414. break;
  96415. case BABYLON.Texture.PROJECTION_MODE:
  96416. defines.REFLECTIONMAP_PROJECTION = true;
  96417. break;
  96418. case BABYLON.Texture.SKYBOX_MODE:
  96419. defines.REFLECTIONMAP_SKYBOX = true;
  96420. break;
  96421. case BABYLON.Texture.SPHERICAL_MODE:
  96422. defines.REFLECTIONMAP_SPHERICAL = true;
  96423. break;
  96424. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96425. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96426. break;
  96427. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96428. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96429. break;
  96430. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96431. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96432. break;
  96433. case BABYLON.Texture.CUBIC_MODE:
  96434. case BABYLON.Texture.INVCUBIC_MODE:
  96435. default:
  96436. defines.REFLECTIONMAP_CUBIC = true;
  96437. break;
  96438. }
  96439. if (this.reflectionFresnel) {
  96440. defines.REFLECTIONFRESNEL = true;
  96441. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96442. this._reflectionControls.x = this.reflectionAmount;
  96443. this._reflectionControls.y = this.reflectionReflectance0;
  96444. this._reflectionControls.z = this.reflectionReflectance90;
  96445. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96446. }
  96447. else {
  96448. defines.REFLECTIONFRESNEL = false;
  96449. defines.REFLECTIONFALLOFF = false;
  96450. }
  96451. }
  96452. else {
  96453. defines.REFLECTION = false;
  96454. defines.REFLECTIONFRESNEL = false;
  96455. defines.REFLECTIONFALLOFF = false;
  96456. defines.REFLECTIONBLUR = false;
  96457. defines.REFLECTIONMAP_3D = false;
  96458. defines.REFLECTIONMAP_SPHERICAL = false;
  96459. defines.REFLECTIONMAP_PLANAR = false;
  96460. defines.REFLECTIONMAP_CUBIC = false;
  96461. defines.REFLECTIONMAP_PROJECTION = false;
  96462. defines.REFLECTIONMAP_SKYBOX = false;
  96463. defines.REFLECTIONMAP_EXPLICIT = false;
  96464. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96465. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96466. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96467. defines.INVERTCUBICMAP = false;
  96468. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96469. defines.LODINREFLECTIONALPHA = false;
  96470. defines.GAMMAREFLECTION = false;
  96471. }
  96472. }
  96473. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96474. defines.USERGBCOLOR = this._useRGBColor;
  96475. defines.NOISE = this._enableNoise;
  96476. }
  96477. if (defines._areLightsDirty) {
  96478. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96479. }
  96480. if (defines._areImageProcessingDirty) {
  96481. if (!this._imageProcessingConfiguration.isReady()) {
  96482. return false;
  96483. }
  96484. this._imageProcessingConfiguration.prepareDefines(defines);
  96485. }
  96486. // Misc.
  96487. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96488. // Values that need to be evaluated on every frame
  96489. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96490. // Attribs
  96491. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96492. if (mesh) {
  96493. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96494. mesh.createNormals(true);
  96495. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96496. }
  96497. }
  96498. }
  96499. // Get correct effect
  96500. if (defines.isDirty) {
  96501. defines.markAsProcessed();
  96502. scene.resetCachedMaterial();
  96503. // Fallbacks
  96504. var fallbacks = new BABYLON.EffectFallbacks();
  96505. if (defines.FOG) {
  96506. fallbacks.addFallback(0, "FOG");
  96507. }
  96508. if (defines.POINTSIZE) {
  96509. fallbacks.addFallback(1, "POINTSIZE");
  96510. }
  96511. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96512. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96513. fallbacks.addCPUSkinningFallback(0, mesh);
  96514. }
  96515. //Attributes
  96516. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96517. if (defines.NORMAL) {
  96518. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96519. }
  96520. if (defines.UV1) {
  96521. attribs.push(BABYLON.VertexBuffer.UVKind);
  96522. }
  96523. if (defines.UV2) {
  96524. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96525. }
  96526. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96527. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96528. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96529. "vFogInfos", "vFogColor", "pointSize",
  96530. "vClipPlane", "mBones",
  96531. "vPrimaryColor", "vPrimaryColorShadow",
  96532. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96533. "shadowLevel", "alpha",
  96534. "vBackgroundCenter", "vReflectionControl",
  96535. "vDiffuseInfos", "diffuseMatrix",
  96536. ];
  96537. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96538. var uniformBuffers = ["Material", "Scene"];
  96539. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96540. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96541. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96542. uniformsNames: uniforms,
  96543. uniformBuffersNames: uniformBuffers,
  96544. samplers: samplers,
  96545. defines: defines,
  96546. maxSimultaneousLights: this._maxSimultaneousLights
  96547. });
  96548. var onCompiled = function (effect) {
  96549. if (_this.onCompiled) {
  96550. _this.onCompiled(effect);
  96551. }
  96552. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96553. };
  96554. var join = defines.toString();
  96555. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96556. attributes: attribs,
  96557. uniformsNames: uniforms,
  96558. uniformBuffersNames: uniformBuffers,
  96559. samplers: samplers,
  96560. defines: join,
  96561. fallbacks: fallbacks,
  96562. onCompiled: onCompiled,
  96563. onError: this.onError,
  96564. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96565. }, engine), defines);
  96566. this.buildUniformLayout();
  96567. }
  96568. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96569. return false;
  96570. }
  96571. defines._renderId = scene.getRenderId();
  96572. this._wasPreviouslyReady = true;
  96573. return true;
  96574. };
  96575. /**
  96576. * Compute the primary color according to the chosen perceptual color.
  96577. */
  96578. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96579. if (!this.__perceptualColor) {
  96580. return;
  96581. }
  96582. this._primaryColor.copyFrom(this.__perceptualColor);
  96583. // Revert gamma space.
  96584. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96585. // Revert image processing configuration.
  96586. if (this._imageProcessingConfiguration) {
  96587. // Revert Exposure.
  96588. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96589. }
  96590. this._computePrimaryColors();
  96591. };
  96592. /**
  96593. * Compute the highlights and shadow colors according to their chosen levels.
  96594. */
  96595. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96596. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96597. return;
  96598. }
  96599. // Find the highlight color based on the configuration.
  96600. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96601. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96602. // Find the shadow color based on the configuration.
  96603. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96604. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96605. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96606. };
  96607. /**
  96608. * Build the uniform buffer used in the material.
  96609. */
  96610. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96611. // Order is important !
  96612. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96613. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96614. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96615. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96616. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96617. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96618. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96619. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96620. this._uniformBuffer.addUniform("pointSize", 1);
  96621. this._uniformBuffer.addUniform("shadowLevel", 1);
  96622. this._uniformBuffer.addUniform("alpha", 1);
  96623. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96624. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96625. this._uniformBuffer.create();
  96626. };
  96627. /**
  96628. * Unbind the material.
  96629. */
  96630. BackgroundMaterial.prototype.unbind = function () {
  96631. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96632. this._uniformBuffer.setTexture("diffuseSampler", null);
  96633. }
  96634. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96635. this._uniformBuffer.setTexture("reflectionSampler", null);
  96636. }
  96637. _super.prototype.unbind.call(this);
  96638. };
  96639. /**
  96640. * Bind only the world matrix to the material.
  96641. * @param world The world matrix to bind.
  96642. */
  96643. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96644. this._activeEffect.setMatrix("world", world);
  96645. };
  96646. /**
  96647. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96648. * @param world The world matrix to bind.
  96649. * @param subMesh The submesh to bind for.
  96650. */
  96651. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96652. var scene = this.getScene();
  96653. var defines = subMesh._materialDefines;
  96654. if (!defines) {
  96655. return;
  96656. }
  96657. var effect = subMesh.effect;
  96658. if (!effect) {
  96659. return;
  96660. }
  96661. this._activeEffect = effect;
  96662. // Matrices
  96663. this.bindOnlyWorldMatrix(world);
  96664. // Bones
  96665. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96666. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96667. if (mustRebind) {
  96668. this._uniformBuffer.bindToEffect(effect, "Material");
  96669. this.bindViewProjection(effect);
  96670. var reflectionTexture = this._reflectionTexture;
  96671. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96672. // Texture uniforms
  96673. if (scene.texturesEnabled) {
  96674. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96675. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96676. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96677. }
  96678. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96679. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96680. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96681. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96682. }
  96683. }
  96684. if (this.shadowLevel > 0) {
  96685. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96686. }
  96687. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96688. // Point size
  96689. if (this.pointsCloud) {
  96690. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96691. }
  96692. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96693. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96694. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96695. }
  96696. else {
  96697. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96698. }
  96699. }
  96700. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96701. // Textures
  96702. if (scene.texturesEnabled) {
  96703. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96704. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96705. }
  96706. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96707. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96708. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96709. }
  96710. else if (!defines.REFLECTIONBLUR) {
  96711. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96712. }
  96713. else {
  96714. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96715. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96716. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96717. }
  96718. if (defines.REFLECTIONFRESNEL) {
  96719. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96720. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96721. }
  96722. }
  96723. }
  96724. // Clip plane
  96725. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96726. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96727. }
  96728. if (mustRebind || !this.isFrozen) {
  96729. if (scene.lightsEnabled) {
  96730. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96731. }
  96732. // View
  96733. this.bindView(effect);
  96734. // Fog
  96735. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96736. // image processing
  96737. this._imageProcessingConfiguration.bind(this._activeEffect);
  96738. }
  96739. this._uniformBuffer.update();
  96740. this._afterBind(mesh);
  96741. };
  96742. /**
  96743. * Dispose the material.
  96744. * @param forceDisposeEffect Force disposal of the associated effect.
  96745. * @param forceDisposeTextures Force disposal of the associated textures.
  96746. */
  96747. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96748. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96749. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96750. if (forceDisposeTextures) {
  96751. if (this.diffuseTexture) {
  96752. this.diffuseTexture.dispose();
  96753. }
  96754. if (this.reflectionTexture) {
  96755. this.reflectionTexture.dispose();
  96756. }
  96757. }
  96758. this._renderTargets.dispose();
  96759. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96760. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96761. }
  96762. _super.prototype.dispose.call(this, forceDisposeEffect);
  96763. };
  96764. /**
  96765. * Clones the material.
  96766. * @param name The cloned name.
  96767. * @returns The cloned material.
  96768. */
  96769. BackgroundMaterial.prototype.clone = function (name) {
  96770. var _this = this;
  96771. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96772. };
  96773. /**
  96774. * Serializes the current material to its JSON representation.
  96775. * @returns The JSON representation.
  96776. */
  96777. BackgroundMaterial.prototype.serialize = function () {
  96778. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96779. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96780. return serializationObject;
  96781. };
  96782. /**
  96783. * Gets the class name of the material
  96784. * @returns "BackgroundMaterial"
  96785. */
  96786. BackgroundMaterial.prototype.getClassName = function () {
  96787. return "BackgroundMaterial";
  96788. };
  96789. /**
  96790. * Parse a JSON input to create back a background material.
  96791. * @param source The JSON data to parse
  96792. * @param scene The scene to create the parsed material in
  96793. * @param rootUrl The root url of the assets the material depends upon
  96794. * @returns the instantiated BackgroundMaterial.
  96795. */
  96796. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96797. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96798. };
  96799. /**
  96800. * Standard reflectance value at parallel view angle.
  96801. */
  96802. BackgroundMaterial.StandardReflectance0 = 0.05;
  96803. /**
  96804. * Standard reflectance value at grazing angle.
  96805. */
  96806. BackgroundMaterial.StandardReflectance90 = 0.5;
  96807. __decorate([
  96808. BABYLON.serializeAsColor3()
  96809. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96810. __decorate([
  96811. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96812. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96813. __decorate([
  96814. BABYLON.serializeAsColor3()
  96815. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96816. __decorate([
  96817. BABYLON.serialize()
  96818. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96819. __decorate([
  96820. BABYLON.serialize()
  96821. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96822. __decorate([
  96823. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96824. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96825. __decorate([
  96826. BABYLON.serializeAsTexture()
  96827. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96828. __decorate([
  96829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96830. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96831. __decorate([
  96832. BABYLON.serialize()
  96833. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96834. __decorate([
  96835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96836. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96837. __decorate([
  96838. BABYLON.serializeAsTexture()
  96839. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96840. __decorate([
  96841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96842. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96843. __decorate([
  96844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96845. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96846. __decorate([
  96847. BABYLON.serialize()
  96848. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96849. __decorate([
  96850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96851. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96852. __decorate([
  96853. BABYLON.serializeAsVector3()
  96854. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96855. __decorate([
  96856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96857. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96858. __decorate([
  96859. BABYLON.serialize()
  96860. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96861. __decorate([
  96862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96863. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96864. __decorate([
  96865. BABYLON.serialize()
  96866. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96867. __decorate([
  96868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96869. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96870. __decorate([
  96871. BABYLON.serialize()
  96872. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96873. __decorate([
  96874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96875. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96876. __decorate([
  96877. BABYLON.serialize()
  96878. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96879. __decorate([
  96880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96881. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96882. __decorate([
  96883. BABYLON.serialize()
  96884. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96885. __decorate([
  96886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96887. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96888. __decorate([
  96889. BABYLON.serialize()
  96890. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96891. __decorate([
  96892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96893. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96894. __decorate([
  96895. BABYLON.serialize()
  96896. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96897. __decorate([
  96898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96899. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96900. __decorate([
  96901. BABYLON.serialize()
  96902. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  96903. __decorate([
  96904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96905. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  96906. __decorate([
  96907. BABYLON.serialize()
  96908. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  96909. __decorate([
  96910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96911. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  96912. __decorate([
  96913. BABYLON.serializeAsImageProcessingConfiguration()
  96914. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  96915. return BackgroundMaterial;
  96916. }(BABYLON.PushMaterial));
  96917. BABYLON.BackgroundMaterial = BackgroundMaterial;
  96918. })(BABYLON || (BABYLON = {}));
  96919. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  96920. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96921. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96922. s = arguments[i];
  96923. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96924. t[p] = s[p];
  96925. }
  96926. return t;
  96927. };
  96928. var BABYLON;
  96929. (function (BABYLON) {
  96930. /**
  96931. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  96932. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  96933. * It also helps with the default setup of your imageProcessing configuration.
  96934. */
  96935. var EnvironmentHelper = /** @class */ (function () {
  96936. /**
  96937. * constructor
  96938. * @param options
  96939. * @param scene The scene to add the material to
  96940. */
  96941. function EnvironmentHelper(options, scene) {
  96942. var _this = this;
  96943. this._errorHandler = function (message, exception) {
  96944. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  96945. };
  96946. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  96947. this._scene = scene;
  96948. this.onErrorObservable = new BABYLON.Observable();
  96949. this._setupBackground();
  96950. this._setupImageProcessing();
  96951. }
  96952. /**
  96953. * Creates the default options for the helper.
  96954. */
  96955. EnvironmentHelper._getDefaultOptions = function () {
  96956. return {
  96957. createGround: true,
  96958. groundSize: 15,
  96959. groundTexture: this._groundTextureCDNUrl,
  96960. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96961. groundOpacity: 0.9,
  96962. enableGroundShadow: true,
  96963. groundShadowLevel: 0.5,
  96964. enableGroundMirror: false,
  96965. groundMirrorSizeRatio: 0.3,
  96966. groundMirrorBlurKernel: 64,
  96967. groundMirrorAmount: 1,
  96968. groundMirrorFresnelWeight: 1,
  96969. groundMirrorFallOffDistance: 0,
  96970. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  96971. groundYBias: 0.00001,
  96972. createSkybox: true,
  96973. skyboxSize: 20,
  96974. skyboxTexture: this._skyboxTextureCDNUrl,
  96975. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96976. backgroundYRotation: 0,
  96977. sizeAuto: true,
  96978. rootPosition: BABYLON.Vector3.Zero(),
  96979. setupImageProcessing: true,
  96980. environmentTexture: this._environmentTextureCDNUrl,
  96981. cameraExposure: 0.8,
  96982. cameraContrast: 1.2,
  96983. toneMappingEnabled: true,
  96984. };
  96985. };
  96986. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  96987. /**
  96988. * Gets the root mesh created by the helper.
  96989. */
  96990. get: function () {
  96991. return this._rootMesh;
  96992. },
  96993. enumerable: true,
  96994. configurable: true
  96995. });
  96996. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  96997. /**
  96998. * Gets the skybox created by the helper.
  96999. */
  97000. get: function () {
  97001. return this._skybox;
  97002. },
  97003. enumerable: true,
  97004. configurable: true
  97005. });
  97006. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97007. /**
  97008. * Gets the skybox texture created by the helper.
  97009. */
  97010. get: function () {
  97011. return this._skyboxTexture;
  97012. },
  97013. enumerable: true,
  97014. configurable: true
  97015. });
  97016. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97017. /**
  97018. * Gets the skybox material created by the helper.
  97019. */
  97020. get: function () {
  97021. return this._skyboxMaterial;
  97022. },
  97023. enumerable: true,
  97024. configurable: true
  97025. });
  97026. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97027. /**
  97028. * Gets the ground mesh created by the helper.
  97029. */
  97030. get: function () {
  97031. return this._ground;
  97032. },
  97033. enumerable: true,
  97034. configurable: true
  97035. });
  97036. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97037. /**
  97038. * Gets the ground texture created by the helper.
  97039. */
  97040. get: function () {
  97041. return this._groundTexture;
  97042. },
  97043. enumerable: true,
  97044. configurable: true
  97045. });
  97046. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97047. /**
  97048. * Gets the ground mirror created by the helper.
  97049. */
  97050. get: function () {
  97051. return this._groundMirror;
  97052. },
  97053. enumerable: true,
  97054. configurable: true
  97055. });
  97056. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97057. /**
  97058. * Gets the ground mirror render list to helps pushing the meshes
  97059. * you wish in the ground reflection.
  97060. */
  97061. get: function () {
  97062. if (this._groundMirror) {
  97063. return this._groundMirror.renderList;
  97064. }
  97065. return null;
  97066. },
  97067. enumerable: true,
  97068. configurable: true
  97069. });
  97070. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97071. /**
  97072. * Gets the ground material created by the helper.
  97073. */
  97074. get: function () {
  97075. return this._groundMaterial;
  97076. },
  97077. enumerable: true,
  97078. configurable: true
  97079. });
  97080. /**
  97081. * Updates the background according to the new options
  97082. * @param options
  97083. */
  97084. EnvironmentHelper.prototype.updateOptions = function (options) {
  97085. var newOptions = __assign({}, this._options, options);
  97086. if (this._ground && !newOptions.createGround) {
  97087. this._ground.dispose();
  97088. this._ground = null;
  97089. }
  97090. if (this._groundMaterial && !newOptions.createGround) {
  97091. this._groundMaterial.dispose();
  97092. this._groundMaterial = null;
  97093. }
  97094. if (this._groundTexture) {
  97095. if (this._options.groundTexture != newOptions.groundTexture) {
  97096. this._groundTexture.dispose();
  97097. this._groundTexture = null;
  97098. }
  97099. }
  97100. if (this._skybox && !newOptions.createSkybox) {
  97101. this._skybox.dispose();
  97102. this._skybox = null;
  97103. }
  97104. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97105. this._skyboxMaterial.dispose();
  97106. this._skyboxMaterial = null;
  97107. }
  97108. if (this._skyboxTexture) {
  97109. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97110. this._skyboxTexture.dispose();
  97111. this._skyboxTexture = null;
  97112. }
  97113. }
  97114. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97115. this._groundMirror.dispose();
  97116. this._groundMirror = null;
  97117. }
  97118. if (this._scene.environmentTexture) {
  97119. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97120. this._scene.environmentTexture.dispose();
  97121. }
  97122. }
  97123. this._options = newOptions;
  97124. this._setupBackground();
  97125. this._setupImageProcessing();
  97126. };
  97127. /**
  97128. * Sets the primary color of all the available elements.
  97129. * @param color the main color to affect to the ground and the background
  97130. */
  97131. EnvironmentHelper.prototype.setMainColor = function (color) {
  97132. if (this.groundMaterial) {
  97133. this.groundMaterial.primaryColor = color;
  97134. }
  97135. if (this.skyboxMaterial) {
  97136. this.skyboxMaterial.primaryColor = color;
  97137. }
  97138. if (this.groundMirror) {
  97139. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97140. }
  97141. };
  97142. /**
  97143. * Setup the image processing according to the specified options.
  97144. */
  97145. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97146. if (this._options.setupImageProcessing) {
  97147. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97148. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97149. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97150. this._setupEnvironmentTexture();
  97151. }
  97152. };
  97153. /**
  97154. * Setup the environment texture according to the specified options.
  97155. */
  97156. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97157. if (this._scene.environmentTexture) {
  97158. return;
  97159. }
  97160. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97161. this._scene.environmentTexture = this._options.environmentTexture;
  97162. return;
  97163. }
  97164. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97165. this._scene.environmentTexture = environmentTexture;
  97166. };
  97167. /**
  97168. * Setup the background according to the specified options.
  97169. */
  97170. EnvironmentHelper.prototype._setupBackground = function () {
  97171. if (!this._rootMesh) {
  97172. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97173. }
  97174. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97175. var sceneSize = this._getSceneSize();
  97176. if (this._options.createGround) {
  97177. this._setupGround(sceneSize);
  97178. this._setupGroundMaterial();
  97179. this._setupGroundDiffuseTexture();
  97180. if (this._options.enableGroundMirror) {
  97181. this._setupGroundMirrorTexture(sceneSize);
  97182. }
  97183. this._setupMirrorInGroundMaterial();
  97184. }
  97185. if (this._options.createSkybox) {
  97186. this._setupSkybox(sceneSize);
  97187. this._setupSkyboxMaterial();
  97188. this._setupSkyboxReflectionTexture();
  97189. }
  97190. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97191. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97192. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97193. };
  97194. /**
  97195. * Get the scene sizes according to the setup.
  97196. */
  97197. EnvironmentHelper.prototype._getSceneSize = function () {
  97198. var _this = this;
  97199. var groundSize = this._options.groundSize;
  97200. var skyboxSize = this._options.skyboxSize;
  97201. var rootPosition = this._options.rootPosition;
  97202. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97203. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97204. }
  97205. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97206. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97207. });
  97208. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97209. if (this._options.sizeAuto) {
  97210. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97211. this._scene.activeCamera.upperRadiusLimit) {
  97212. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97213. skyboxSize = groundSize;
  97214. }
  97215. var sceneDiagonalLenght = sceneDiagonal.length();
  97216. if (sceneDiagonalLenght > groundSize) {
  97217. groundSize = sceneDiagonalLenght * 2;
  97218. skyboxSize = groundSize;
  97219. }
  97220. // 10 % bigger.
  97221. groundSize *= 1.1;
  97222. skyboxSize *= 1.5;
  97223. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97224. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97225. }
  97226. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97227. };
  97228. /**
  97229. * Setup the ground according to the specified options.
  97230. */
  97231. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97232. var _this = this;
  97233. if (!this._ground) {
  97234. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97235. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97236. this._ground.parent = this._rootMesh;
  97237. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97238. }
  97239. this._ground.receiveShadows = this._options.enableGroundShadow;
  97240. };
  97241. /**
  97242. * Setup the ground material according to the specified options.
  97243. */
  97244. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97245. if (!this._groundMaterial) {
  97246. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97247. }
  97248. this._groundMaterial.alpha = this._options.groundOpacity;
  97249. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97250. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97251. this._groundMaterial.primaryColor = this._options.groundColor;
  97252. this._groundMaterial.useRGBColor = false;
  97253. this._groundMaterial.enableNoise = true;
  97254. if (this._ground) {
  97255. this._ground.material = this._groundMaterial;
  97256. }
  97257. };
  97258. /**
  97259. * Setup the ground diffuse texture according to the specified options.
  97260. */
  97261. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97262. if (!this._groundMaterial) {
  97263. return;
  97264. }
  97265. if (this._groundTexture) {
  97266. return;
  97267. }
  97268. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97269. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97270. return;
  97271. }
  97272. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97273. diffuseTexture.gammaSpace = false;
  97274. diffuseTexture.hasAlpha = true;
  97275. this._groundMaterial.diffuseTexture = diffuseTexture;
  97276. };
  97277. /**
  97278. * Setup the ground mirror texture according to the specified options.
  97279. */
  97280. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97281. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97282. if (!this._groundMirror) {
  97283. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97284. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97285. this._groundMirror.anisotropicFilteringLevel = 1;
  97286. this._groundMirror.wrapU = wrapping;
  97287. this._groundMirror.wrapV = wrapping;
  97288. this._groundMirror.gammaSpace = false;
  97289. if (this._groundMirror.renderList) {
  97290. for (var i = 0; i < this._scene.meshes.length; i++) {
  97291. var mesh = this._scene.meshes[i];
  97292. if (mesh !== this._ground &&
  97293. mesh !== this._skybox &&
  97294. mesh !== this._rootMesh) {
  97295. this._groundMirror.renderList.push(mesh);
  97296. }
  97297. }
  97298. }
  97299. }
  97300. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97301. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97302. };
  97303. /**
  97304. * Setup the ground to receive the mirror texture.
  97305. */
  97306. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97307. if (this._groundMaterial) {
  97308. this._groundMaterial.reflectionTexture = this._groundMirror;
  97309. this._groundMaterial.reflectionFresnel = true;
  97310. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97311. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97312. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97313. }
  97314. };
  97315. /**
  97316. * Setup the skybox according to the specified options.
  97317. */
  97318. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97319. var _this = this;
  97320. if (!this._skybox) {
  97321. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97322. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97323. }
  97324. this._skybox.parent = this._rootMesh;
  97325. };
  97326. /**
  97327. * Setup the skybox material according to the specified options.
  97328. */
  97329. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97330. if (!this._skybox) {
  97331. return;
  97332. }
  97333. if (!this._skyboxMaterial) {
  97334. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97335. }
  97336. this._skyboxMaterial.useRGBColor = false;
  97337. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97338. this._skyboxMaterial.enableNoise = true;
  97339. this._skybox.material = this._skyboxMaterial;
  97340. };
  97341. /**
  97342. * Setup the skybox reflection texture according to the specified options.
  97343. */
  97344. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97345. if (!this._skyboxMaterial) {
  97346. return;
  97347. }
  97348. if (this._skyboxTexture) {
  97349. return;
  97350. }
  97351. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97352. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97353. return;
  97354. }
  97355. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97356. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97357. this._skyboxTexture.gammaSpace = false;
  97358. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97359. };
  97360. /**
  97361. * Dispose all the elements created by the Helper.
  97362. */
  97363. EnvironmentHelper.prototype.dispose = function () {
  97364. if (this._groundMaterial) {
  97365. this._groundMaterial.dispose(true, true);
  97366. }
  97367. if (this._skyboxMaterial) {
  97368. this._skyboxMaterial.dispose(true, true);
  97369. }
  97370. this._rootMesh.dispose(false);
  97371. };
  97372. /**
  97373. * Default ground texture URL.
  97374. */
  97375. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97376. /**
  97377. * Default skybox texture URL.
  97378. */
  97379. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97380. /**
  97381. * Default environment texture URL.
  97382. */
  97383. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97384. return EnvironmentHelper;
  97385. }());
  97386. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97387. })(BABYLON || (BABYLON = {}));
  97388. //# sourceMappingURL=babylon.environmentHelper.js.map
  97389. var BABYLON;
  97390. (function (BABYLON) {
  97391. /**
  97392. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97393. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97394. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97395. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97396. */
  97397. var VideoDome = /** @class */ (function (_super) {
  97398. __extends(VideoDome, _super);
  97399. /**
  97400. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97401. * @param name Element's name, child elements will append suffixes for their own names.
  97402. * @param urlsOrVideo
  97403. * @param options An object containing optional or exposed sub element properties:
  97404. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97405. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97406. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97407. * @param options **loop=true** Automatically loop video on end.
  97408. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97409. */
  97410. function VideoDome(name, urlsOrVideo, options, scene) {
  97411. var _this = _super.call(this, name, scene) || this;
  97412. // set defaults and manage values
  97413. name = name || "videoDome";
  97414. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97415. options.clickToPlay = Boolean(options.clickToPlay);
  97416. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97417. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97418. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97419. // create
  97420. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97421. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97422. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97423. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97424. flat: false,
  97425. radius: options.size,
  97426. subdivisions: options.resolution,
  97427. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97428. }, scene);
  97429. // configure material
  97430. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97431. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97432. material.reflectionTexture = _this._videoTexture;
  97433. material.useEquirectangularFOV = true;
  97434. material.fovMultiplier = 1.0;
  97435. // configure mesh
  97436. _this._mesh.material = material;
  97437. _this._mesh.parent = _this;
  97438. // optional configuration
  97439. if (options.clickToPlay) {
  97440. scene.onPointerUp = function () {
  97441. _this._videoTexture.video.play();
  97442. };
  97443. }
  97444. return _this;
  97445. }
  97446. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97447. /**
  97448. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97449. * Also see the options.resolution property.
  97450. */
  97451. get: function () {
  97452. return this._material.fovMultiplier;
  97453. },
  97454. set: function (value) {
  97455. this._material.fovMultiplier = value;
  97456. },
  97457. enumerable: true,
  97458. configurable: true
  97459. });
  97460. /**
  97461. * Releases resources associated with this node.
  97462. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97463. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97464. */
  97465. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97466. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97467. this._videoTexture.dispose();
  97468. this._mesh.dispose();
  97469. this._material.dispose();
  97470. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97471. };
  97472. return VideoDome;
  97473. }(BABYLON.Node));
  97474. BABYLON.VideoDome = VideoDome;
  97475. })(BABYLON || (BABYLON = {}));
  97476. //# sourceMappingURL=babylon.videoDome.js.map
  97477. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  97478. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  97479. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  97480. globalObject["BABYLON"] = BABYLON;
  97481. //backwards compatibility
  97482. if(typeof earcut !== 'undefined') {
  97483. globalObject["Earcut"] = {
  97484. earcut: earcut
  97485. };
  97486. }
  97487. return BABYLON;
  97488. });